我正在尝试在文本文件中替换将以path ='/ users / username / folder'形式的字符串。我正在读取该文本文件并搜索从'path ='开始的行。我有两个问题,
请帮忙。
f = open('/Volumes/Personal/example.text','r+')
for line in f:
print(line, end='')
if (line.startswith("path = ")):
# You need to include a newline if you're replacing the whole line
line = CurrentFilePath + "\n"
f.write(line)
print ("Success!!!!")
答案 0 :(得分:2)
您可以使用正则表达式。
import re
with open("filename","r+") as f:
text = f.read()
modified_text, modified = re.subn(r'(?:^|(?<=\n))path\s\=.*',CurrentFilePath, text)
if modified:
print ("Success!!!!")
else:
print ("Failure :(")
f.seek(0)
f.write(modified_text)
f.truncate()