如何在文本文件中搜索一个词,然后用python中的新行替换整行?

2024-04-25 13:15:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到这个,但我最终找到的代码,取代了一个特定的词。 我一直在使用这个代码:

phrase = open(club, 'a')
    for line in phrase:
        if line.contains(name):
            #what do i put here?
        else:
            pass
else:
    pass 

假设我有一个包含sam 10的文本文件,我想用sam 5替换它。如果我用上面的代码做这个,我会怎么做?名字会保持不变,但号码不会。因为每个名字的号码都不一样,所以我无法搜索号码,这就是我搜索名字的原因。我在考虑使用line.replace,但这只改变了一个短语,而我希望整行都改变。你知道吗

编辑:这是在假设文本文件中有多个不同的人的名字和不同的数字的情况下进行的。我想让它搜索那个特定的名字并替换整行。你知道吗

谢谢!你知道吗


Tags: 代码inforifsamlinepassopen
2条回答

您可以逐行检查以修改,也可以修改原始以保存更改:

f = open('sample.txt', 'r')
lines = f.readlines()
f.close()
name = 'ali'

for i in range(len(lines) - 1):
    line = lines[i]
    #Find 'name' index (-1 if not found)
    index = line.find(name)
    # If the wanted name is found
    if index != -1:
       #Split line by spaces to get name and number starting from name

       words = line[index:].split()
       # Name and number should be the first two elements in words list
       name_number =  words[0]+ ' ' + '5' #words[1]

       #
       # Do some thing with name_number
       #

       # the last '1' is to skip copying a space
       line  = line[:index] + name_number + ' ' + line[index + len(name_number) + 1:]

       # Save result
       lines[i] = line

output = open('sample.txt', 'w')
for line in lines:
    output.write(line)
output.close()

一般来说,有很多方法,其中之一是:

使用内置方法:

with open(club, 'r') as in_file, open('new_file', 'w') as out_file:
    for line in in_file:
        if name in line:
            out_file.write(new_line)
        else: 
            out_file.write(line)

但这会产生创建新文件的效果。你知道吗

编辑:

如果您想进行就地替换,那么可以使用^{}模块,方法如下:

for line in fileinput.input(club, inplace=True):
    if name in line:
        line = 'NEW LINE' #Construct your new line here
        print(line) #This will print it into the file 
    else:
        print(line) #No Changes to be made, print line into the file as it is

引用docs

class fileinput.FileInput(files=None, inplace=False, backup='', bufsize=0, mode='r', openhook=None)
...
Optional in-place filtering: if the keyword argument inplace=True is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place.

相关问题 更多 >