2017-04-19 4 views
0

를 읽을 다음 쓰기 :파이썬 - 나는 다음과 같은 파이썬 코드 작성 파일

# code that reads the file line by line 
def read_the_file(file_to_read): 
    f = open('test.nml','r') 
    line = f.readline() 
    print("1. Line is : ", line) 
    if '<?xml version="1.0"' in line: 
     next_line = f.readline() 
     print("2. Next line is : ", next_line) 
     write_f = open('myfile', 'w') 
     while '</doc>' not in next_line: 
      write_f.write(next_line) 
      next_line = f.readline() 
      print("3. Next line is : ", next_line) 
     write_f.close() 
    return write_f 

# code that processes the xml file 
def process_the_xml_file(file_to_process): 
    print("5. File to process is : ", file_to_process) 
    file = open(file_to_process, 'r') 
    lines=file.readlines() 
    print(lines) 
    file.close() 


# calling the code to read the file and process the xml 
path_to_file='test.nml' 
write_f=read_the_file(path_to_file) 
print("4. Write f is : ", write_f) 
process_the_xml_file(write_f) 

기본적으로 먼저 작성하고 다음 파일을 읽으려고합니다. 코드는 다음 오류를 제공합니다 :

TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper 

어떤 아이디어를 잘못하고 어떻게 해결할 수 있습니까? 감사.

+1

전체 오류 메시지를 표시 할 수 있습니까? ?? – shiva

+1

오류는 발생하는 줄 번호도 제공해야합니다. –

+0

동일한 문제가있는 코드를 최소한으로 만들어보십시오. [mcve]를 만드는 방법을 참조하십시오. –

답변

0

read_the_file의 return write_freturn write_f.name으로 바꿉니다.

write_f가 파일 처리기 객체이므로 파일 처리기 객체가 아닌 process_the_xml_file에 파일 이름을 전달해야합니다.

+1

나는 이것이 일을 끝내는 감사하다고 생각한다. 더 이상의 질문이있을 것입니다. – adrCoder

1

여기서 문제는 process_the_xml_file 메소드에서 문자열이 아닌 닫힌 파일 핸들을 사용하고 있다는 것입니다.

read_the_file은 파일 핸들이 아닌 파일 핸들을 반환합니다.

+1

'read_the_file' 함수에서'write_f.name'을 리턴 할 수 있습니다. – poke

관련 문제