2017-04-19 77 views
0

我寫了下面的Python代碼:Python的 - 寫然後讀取文件

# 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_f替換爲return 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

相關問題