尝试打开文件时出现类型错误

尝试打开文件时出现类型错误

问题描述:

我编写了以下 Python 代码:

I wrote the following Python code:

# 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)

基本上尝试先写入然后读取文件.该代码给出了以下错误:

which basically attempts to first write and then read a file. The code gives the following error:

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

任何想法我做错了什么以及如何解决它?谢谢.

Any ideas what I am doing wrong and how to fix it? Thanks.

将 read_the_file 中的 return write_f 替换为 return write_f.name.

Replace return write_f in read_the_file to return write_f.name.

write_f 是文件处理程序对象,您需要将文件名传递给 process_the_xml_file,而不是文件处理程序对象.

write_f is the file handler object, you need to pass the name of the file to process_the_xml_file, not the file handler object.