简体   繁体   English

我应该如何替换文件中特定行中的单词(python)

[英]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.

相关问题 如何通过不触摸 python 中文本文件的每一行中该单词的 rest 来替换每行中的第一个特定特殊字符 - How to replace the first specific special character in each line by not touching the rest of that word in each of the line of a text file in python 如何从“关键字” python开始替换特定行中的特定单词 - How to replace a specific word in specific line starting with a “keyword” python Python:如何替换文本文件中一行的最后一个单词? - Python: How to replace the last word of a line from a text file? Python 如何替换文本文件中特定行中的特定单词? - Python How to replace a particular word in a particular line in a text file? 如何使用python替换文本文件中某些特定单词的字符 - How to replace a character in some specific word in a text file using python 如何在python中的文本文件中删除特定单词之前的一行 - How to delete one line before a specific word in a text file in python 如何用 python 替换文件的特定行? - How do you replace a specific line of a file with python? 用Python将文本文件中的单词替换为特定列中的单词 - Replace word in text file comma separated with word in a specific column with Python 如何在python中替换特定单词下的值? - how to replace a value under specific word in python? 如何用python替换句子中的特定单词 - how to replace specific word in a sentence with python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM