我正在尝试将文件中的一行替换为长度因输入而异的字符串。如果字符串的长度等于或大于要替换的行,则文件被正确覆盖。反之,如果字符串比要替换的行短,则替换后,行的一部分将被附加到末尾。
用于写入该文件的代码片段如下所示。
replace_value = status
lines = []
filename = open(os.path.join(dst_path, asilSafety_path),'r+')
for line in filename.readlines():
line.strip('\n')
if line.startswith('export SAFETY_SRV_MODE'):
bits = line.split('=')
config, value = bits
src = config + '=' + value.strip('\n')
target = config + '= ' + replace_value
break
filename.seek(0)
for line in filename.readlines():
line = line.replace(src,target)
lines.append(line)
filename.seek(0)
for line in lines:
filename.write(line)
filename.close()
我将文件路径和字符串作为参数传递给函数,即safety_configuration(dst_path,status)。变量'replace_value‘包含要替换的字符串。
有没有人能告诉我,我做错了什么?或者,有没有其他方法来实现这一点?
发布于 2014-07-16 07:40:40
import fileinput
import sys
count = 0
replace_value = status
for line in fileinput.input(["a.txt"], inplace=True, backup='.bak'):
if line.startswith('export SAFETY_SRV_MODE'):
bits = line.split('=')
config, value = bits
src = config + '=' + value.strip('\n')
target = config + '= ' + replace_value+"\n"
sys.stdout.write(line.replace(src,target))
else:
sys.stdout.write(line)
为此,您可以使用文件输入,而不是上下移动文件,您可以在找到文件时对其进行更改
发布于 2014-07-16 07:44:36
我建议循环遍历文件中的行一次,如果它们与您想要替换的行不匹配,只需将它们附加到lines
。
如果有,请在将该行附加到lines
之前对其进行修改。只需将它们重写到文件中。
replace_value = status
lines = []
with open(os.path.join(dst_path, asilSafety_path)) as f:
for line in f:
if line.startswith('export SAFETY_SRV_MODE'):
config, value = line.split('=')
lines.append(config + '= ' + replace_value + '\n')
else:
lines.append(line)
with open(os.path.join(dst_path, asilSafety_path), 'w') as f:
f.writelines(lines)
发布于 2014-07-16 08:32:56
如果您有足够的内存来加载整个文件,那么您的解决方案是正确的。您只是忘记了truncate
文件对象,这就是为什么您在最后看到垃圾的原因。
脚本的最后一部分应该是:
filename.seek(0)
for line in lines:
filename.write(line)
filename.truncate()
filename.close()
您也可以在seek
之后立即截断。
https://stackoverflow.com/questions/24774694
复制