[英]How to replace a specific word in specific line starting with a “keyword” python
我试图编写python代码来执行以下操作,但遇到了麻烦。 请帮忙。
我有这个文件“ names.txt”
rainbow like to play football however rainbow ... etc names = rainbow, john, alex rainbow sdlsdmclscmlsmcldsc.
我需要将彩虹字替换为(已删除)以“ name =”开头的行
我需要代码来搜索关键字“ name =”,并在同一行中将单词“ rainbow”替换为“(已删除)”,而无需更改其他行中的Rainbow单词,然后用所做的更改覆盖文件“ names.txt”像是:
rainbow like to play football however rainbow ... etc names = (Removed), john, alex rainbow sdlsdmclscmlsmcldsc.
谢谢
避免正则表达式,这是一种实现方式
with open("names.txt") as f:
content = f.readlines()
我如何将文件逐行读入列表中进行了说明? 并且被发现使用谷歌搜索“在文件python中读取堆栈溢出的最佳方式”。 然后获取此内容,然后执行以下操作。
new_list_full_of_lines = [] # This is what you are going to store your corrected list with
for linea in content: # This is looping through every line
if "names =" in linea:
linea.replace ("rainbow", "(Removed)") # This corrects the line if it needs to be corrected - i.e. if the line contanes "names =" at any point
new_list_full_of_lines.append(linea) # This saves the line to the new list
with open('names.txt', 'w') as f: # This will write over the file
for item in new_list_full_of_lines: # This will loop through each line
f.write("%s\n" % item) # This will ensure that there is a line space between each line.
参考- 字符串替换似乎不起作用
其他参考- 使用Python将列表写入文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.