【发布时间】: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