How to save the file using fileinput in python? Giving AttributeError: 'FileInput' object has no attribute 'read'

How to save the file using fileinput in python? Giving AttributeError: 'FileInput' object has no attribute 'read'

我正在使用 fileinput 模块保存文件但抛出 AttributeError:'FileInput' 对象没有属性 '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:不可读

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

if I am using normal mode i am getting io.UnsupportedOperation: not readable

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

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