【问题标题】:TypeError when trying to open file尝试打开文件时出现类型错误
【发布时间】:2019-03-13 19:46:31
【问题描述】:

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

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

【问题讨论】:

  • 你能显示完整的错误信息吗..??
  • 错误还应该给出它发生的行号。
  • 尝试创建具有相同问题的最小代码段。了解如何创建minimal reproducible example
  • 两个注意事项:1.您在if 语句中创建write_f,然后在read_the_file 中返回它。考虑如果不执行if 语句会发生什么。 2. 在if 语句中,您将关闭write_f 文件(之后立即返回)。

标签: python typeerror


【解决方案1】:

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

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

【讨论】:

  • 你可以在read_the_file函数中return write_f.name
【解决方案2】:

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

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

【讨论】:

  • 我认为这可以完成工作,谢谢。将返回任何更多查询。
猜你喜欢
  • 2020-11-17
  • 1970-01-01
  • 2011-10-06
  • 2017-10-02
  • 2013-02-06
  • 2016-11-03
  • 1970-01-01
  • 1970-01-01
  • 2017-09-28
相关资源
最近更新 更多