这是在文件上查找/替换的代码:
def updateFiles():
fileToUpdt = tup[0]
origVal = tup[1]
newVal = tup[2]
curfiledata = None
with open(fileToUpdt, 'r') as curfile :
curfiledata = curfile.read()
curfiledata = curfiledata.replace(origVal, newVal)
with open(fileToUpdt, 'w') as curfile:
curfile.write(curfiledata)
问题在于输入文件中的行有时为CRLF,有时仅为LF,但是write命令始终返回CRLF。当原始行是LF时,我希望它保留该换行符,而不要放在CR中。换句话说,换行符应始终与输入文件中的原始换行符相同,因此,如果换行符为CRLF,则应保持为CRLF,但如果换行符为LF,则应保持为LF。有办法可以做到吗?
最佳答案
首先,将b
(二进制)添加到读/写模式,以使python忽略行并将文件视为二进制。
with open(fileToUpdt, 'rb') as curfile :
curfiledata = curfile.read()
和
with open(fileToUpdt, 'wb') as curfile:
curfile.write(curfiledata)
在python 2中就足够了,但是在Python 3中,
curfiledata
的类型为bytes
,不再是str
,因为它是由二进制流返回的,因此必须确保origVal
和newVal
是bytes
而不是str
,例如通过在encode
对象上使用str
。origVal = tup[1].encode()
newVal = tup[2].encode()
(取决于数据,您可能必须对
encode
使用额外的参数:例如:encode("utf-8")