2017-11-21 12 views
1

-a 스위치에서 설정 파일에 텍스트를 추가하려고합니다. 나머지 코드는 작동하지만 select config 파일을 호출하고 백업 할 새 파일을 작성할 사람이 누구인지 확실하지 않습니다. 내가이 실행 파일에 텍스트를 추가하십시오. 지정된 txt 파일에 텍스트를 추가합니다.

parser = argparse.ArgumentParser(description='Copy multiple Files from a specified data file') 
parser.add_argument('-c', '--configfile', default="config.dat", help='file to read the config from') 
parser.add_argument('-l', '--location', default="/home/admin/Documents/backup/",help='Choose location to store files') 
parser.add_argument('-a', '--addfile', help='Choose a file to add to list') 

def read_config(data): 
    try: 
     dest = '/home/admin/Documents/backup/' 
     # Read in date from config.dat 
     data = open(data) 
     # Interate through list of files '\n' 
     filelist = data.read().split('\n') 
     # Copy through interated list and strip white spaces and empty lines 
     for file in filelist: 
      if file: 
       shutil.copy(file.strip(), dest) 
    except FileNotFoundError: 
     logger.error("Config file not found") 
     print ("Config File not found") 

def add_to_file(): 
    try: 
     f = open('configfile','r') 
     f.read() 
     addto = f.write('addfile') 
     f.close() 
    except FileNotFoundError: 
      pass** 
args = vars(parser.parse_args()) 
read = read_config(args['configfile']) 
add = add_to_file(args['addfile']) 

나는 다음과 같은 오류가 발생 :

add = add_to_file(args['addfile']) 
TypeError: add_to_file() takes 0 positional arguments but 1 was given 

어떤 아이디어 나는이 문제 하겠어 어디? 어떤 도움

답변

2

오류에 대한

덕분에 거기에 문제가 있습니다

add_to_file() takes 0 positional arguments but 1 was given 

add_to_file

어떤 인수를 고려하지 않습니다,하지만 당신은 하나를 통과하고 있습니다.

편집 : 잘못 여기에 몇 가지가 있지만 내 원래의 대답은 즉각적인 장애물이다

  1. f.write가 할당 할 필요가 없습니다, 아무것도 반환하지 않습니다.
  2. read_config에서 파일을 닫지 마십시오.
  3. 이 파일에 추가하려면 다음과 같이 a 모드를 열 필요가 : 당신은 블록을 제외하고 당신에 지나치게 들여 쓰기있어 open('configfile', 'a') 대신
  4. 모드 r의. 또한 나는 어떤 패스가 ** 있는지도 모르겠다. 당신은 아마 그것이 인상하도록해야합니다.
  5. 여기에서 코드가 수행하려고하는 것이 확실하지 않습니다. read_config는 파일 목록을 읽은 다음 dest에 복사합니다. 알 겠어. 그렇다면 add_to_file은 무엇을합니까? read_config의 후속 실행에서 복사 될 config에 파일을 더 추가 하시겠습니까?

# 2의 경우 컨텍스트 관리자를 사용하는 것이 좋습니다. 그것은 당신을 위해 파일을 닫는 처리합니다.

with open('some_file.txt', 'r'): 
    do_some_stuff() 

위 예제는 예외가 있더라도 파일 열기 및 닫기를 처리합니다.

+0

도움 주셔서 감사합니다. 나는 변경 다음 데프 addtofile (시험) : 시도 : 개방 ('config.dat', 'A')와 파일로 : FileNotFoundError 제외 file.write가 (테스트 + "\ n을") : logger.error ("오류 메시지") 인수의 = 용 VARS (parser.parse_args()) 판독 = read_config (인수 [ '에서 configFile']) 추가 = addtofile (인수는 [ '추가']) 또 shutil .SameFileError : 'backup/test.dat'및 '/home/admin/Documents/backup/test.dat'는 동일한 파일입니다. –