gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:21:37 24 4
gpt4 key购买 nike

我编写了以下 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

你知道我做错了什么以及如何解决它吗?谢谢。

最佳答案

这里的问题是您使用的是关闭的文件句柄,而不是 process_the_xml_file 方法中的字符串。

read_the_file 返回文件句柄,而不是文件名。

关于python - 尝试打开文件时出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43490993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com