【问题标题】:How to save the file using fileinput in python? Giving AttributeError: 'FileInput' object has no attribute 'read'如何在python中使用fileinput保存文件?给出 AttributeError:'FileInput' 对象没有属性 'read'
【发布时间】:2019-06-24 12:59:21
【问题描述】:

我正在使用 fileinput 模块保存文件但抛出 AttributeError: 'FileInput' object has no attribute 'read'

我已通过查看一些堆栈溢出问题来关闭文件

 import re
 import fileinput
 rx = r'\d+(?=:$)'
 with fileinput.input('branch.txt', inplace=True) as fh:
    data = fh.read()
    print(re.sub(rx , lambda x: str(int(x.group(0)) + 1), data, 1, re.M))
    data.close()
    fh.close

如果我使用普通模式,我会得到 io.UnsupportedOperation: not readable

 import re
 rx = r'\d+(?=:$)'
 with open('branch.txt','a') as fh:
    fh_n = fh.read()
    x = (re.sub(rx, lambda x: str(int(x.group(0)) + 1), fh_n, 1, re.M))
    #print (x)
    fh.write(x)
    fh.close()

【问题讨论】:

  • 你为什么要fileinput而不是内置的open
  • import re rx = r'\d+(?=:$)' with open('branch.txt','a') as fh: fh_n = fh.read() x = (re .sub(rx, lambda x: str(int(x.group(0)) + 1), fh_n, 1, re.M)) print (x) fh.write(x) fh.close() 得到错误 io .UnsupportedOperation:不可读
  • 那么,您只想读取和写入同一个文件吗?见Search and replace a line in a file in Python
  • 是的,我正在尝试这样做。代码有问题吗。因为阅读模式运行良好

标签: python regex python-3.x file-io


【解决方案1】:

如果我使用普通模式,我会得到 io.UnsupportedOperation: not readable

 import re
 …
 with open('branch.txt','a') as fh:

这是因为无法读取以'a'(附加)模式打开的文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 2015-07-31
    • 2020-10-27
    相关资源
    最近更新 更多