DPl*_*eis 4 python replace file python-3.x
我有一个文本文件中的字符串列表。弦是早晨、夜晚、太阳、月亮。我想要做的是用另一个字符串替换这些字符串之一。例如,我会输入morning 以将其删除并替换为下午。当字符串明显在列表中时,我收到一条错误消息:“builtins.ValueError: list.remove(x): x not in list”。
def main():
x = input("Enter a file name: ")
file = open(x , "r+")
y = input("Enter the string you want to replace: ")
z = input("Enter the string you to replace it with: ")
list = file.readlines()
list.remove(y)
list.append(z)
file.write(list)
print(file.read())
main()
Run Code Online (Sandbox Code Playgroud)
如果有更好的方法可以通过另一种方式实现相同的结果,请告诉我。谢谢您的帮助!
这里有一些想法:
该str.replace()函数是替换字符串的最简单的方法,s.replace(y, z)
。
该应用re.sub()函数可以让你搜索模式和使用字符串替换:re.sub(y, z, s)
。
该的FileInput模块将允许你就地修改。
这是一种方法:
import fileinput
import re
with fileinput.input(files=('file1.txt', 'file2.txt'), inplace=True) as f:
for line in f:
print( re.sub(y, z, line) )
Run Code Online (Sandbox Code Playgroud)
这是另一个想法:
例如:
import re
with open(filename) as f:
s = f.read()
with open(filename, 'w') as f:
s = re.sub(y, z, s)
f.write(s)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8019 次 |
最近记录: |