[英]How should i replace a word in a specific line in a file (python)
I have one file called tenantdetails(tdetails.txt) I want to replace one of the data inside but the other similar data I dont want them to be affected.我有一个名为tenantdetails(tdetails.txt) 的文件,我想替换其中的一个数据,但我不希望它们受到影响的其他类似数据。 This is my file:这是我的文件:
T001,ly,0500505,male,17,johor,butterworth ,adam,long,
T002,ll,06060606,female,19,johor,kl,lili ,short,
T003,xh,030303,male,17,juru,hotel,adik,...,
So, this is my code:所以,这是我的代码:
def word_search(key, filename):
with open(filename,"r") as file: # opening the file using with to ensure it closes after the block of code is executed
lines = file.readlines() # reading the lines of the files in order
for number, line in enumerate(lines, 1): # using enumerate to map each line of the file to it's line_number
if key in line: # searching for the keyword in file
return( number) # returning the line number if the keyword
def replace_line(file,old,new):
key=input("Enter keyword")
line_num=word_search(key,file)
print(line_num)
filedata=''
with open(file,"r") as f:
for line in f:
if old in line[line_num]:
line= line.replace(old, new)
filedata += line
with open(file,"w") as f:
f.write(filedata)
How should i change the Johor for T001, but T002 will not affected我应该如何将柔佛换成T001,但T002不受影响
Loop through every line and when the correct line is found loop through every word until the correct word is found.遍历每一行,当找到正确的行时,遍历每个单词,直到找到正确的单词。
I would recommend that instead of trying to edit the line in the file you completely rewrite the file with the edited line.我建议不要尝试编辑文件中的行,而是用编辑的行完全重写文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.