简体   繁体   English

搜索单词,并使用 fileinput 在 Python 文件中替换包含该单词的整行

[英]Search the word, and replace the whole line containing the word in a file in Python using fileinput

I want to search a particular word in a text file.我想在文本文件中搜索特定的单词。 For each line,where the word is present, I want to completely change the line by a new text.对于出现单词的每一行,我想用新文本完全更改该行。

I want to achieve this using fileinput module of python.我想使用 python 的fileinput模块来实现这一点。 There are two observation, I am seeing with following variations:-有两个观察结果,我看到有以下变化:-

Code piece 1:-代码片段 1:-

text = "mov9 = "   # if any line contains this text, I want to modify the whole line.
new_text = "mov9 = Alice in Wonderland"
x = fileinput.input(files="C:\Users\Admin\Desktop\DeletedMovies.txt", inplace=1)
for line in x:
    if text in line:
        line = new_text
        print line,
x.close()

The above piece of code wipes out all the content of the file, and writes the new_text ie the file content is only上面这段代码把文件的所有内容都抹掉,写入new_text即文件内容只有

mov9 = Alice in Wonderland mov9 = 爱丽丝梦游仙境

Code Piece 2:-代码片段 2:-

text = "mov9 = "   # if any line contains this text, I want to modify the whole line.
new_text = "mov9 = Alice in Wonderland"
x = fileinput.input(files="C:\Users\Admin\Desktop\DeletedMovies.txt", inplace=1)
for line in x:
    if text in line:
        line = line.replace(text, new_text)
        print line,
x.close()

The above piece of code, even though adds the needed line ie new_text where text is found, but doesn't deletes the line, but keeps the previous data also.上面的代码,即使在找到text的地方添加了所需的行,即new_text ,但不会删除该行,但还会保留以前的数据。

That is if the line was earlier:-那就是如果该行更早:-

mov9 = Fast & Furios

after running the above piece of code it becomes:-运行上面的代码后,它变成了:-

mov9 = Alice in WonderlandFast & Furios

And other content of the files remain untouched, not deleted as in code in Code piece 1.文件的其他内容保持不变,不会像代码段 1 中的代码那样被删除。

But my goal is to find the word mov9 = , and whatever is present along with it, I want to replace the whole line as mov9 = Alice in Wonderland .但我的目标是找到单词mov9 =以及与之一起出现的任何内容,我想将整行替换为mov9 = Alice in Wonderland

How can I achieve that?我怎样才能做到这一点? Thanks in advance....提前致谢....

I realized that I was wrong by just an indentation.我意识到我错了,只是一个缩进。 In the code piece 1 mentioned in the question, if I am bringing the 'print line,' from the scope of if ie if i outdent it, then this is solved...在问题中提到的代码片段 1 中,如果我从 if 的范围内带来“打印行”,即如果我缩进它,那么这就解决了......

As this line was inside the scope of if , hence, only this new_text was being written to the file, and other lines were not being written, and hence the file was left with only the new_text .由于这一行在if的范围内,因此,只有这个new_text被写入文件,而其他行没有被写入,因此文件只剩下new_text So, the code piece should be as follow:-因此,代码片段应如下所示:-

text = "mov9 = "   # if any line contains this text, I want to modify the whole line.
new_text = "mov9 = Alice in Wonderland"
x = fileinput.input(files="C:\Users\Admin\Desktop\DeletedMovies.txt", inplace=1)
for line in x:
    if text in line:
        line = new_text
    print line,
x.close()

Also, the second solution given by Rolf of Saxony & the first solution by Padraic Cunningham is somehow similar.此外, Rolf of Saxony给出的第二个解决方案和Padraic Cunningham给出的第一个解决方案在某种程度上是相似的。

You empty you file because you only write when you find a match, you need to always write the lines:你清空你的文件,因为你只在找到匹配项时才写,你需要始终写下这些行:

import sys

text = "mov9 = "   # if any line contains this text, I want to modify the whole line.
new_text = "mov9 = Alice in Wonderland\n"

x = fileinput.input(files="C:\Users\Admin\Desktop\DeletedMovies.txt", inplace=1)
for line in x:
    if text in line:
        line = new_text
    sys.stdout.write(line)

If you find a match the line will be set to new_text , so either sys.stdout.write(line) will write the original line or new_text .如果找到匹配项,该行将设置为new_text ,因此sys.stdout.write(line)将写入原始行或new_text Also if you actually want to find lines starting with text use if line.startswith(text):此外,如果您确实想查找以text开头的行,请使用if line.startswith(text):

You could also write to a tempfile and replace the original:您还可以写入tempfile并替换原始文件:

from shutil import move
from tempfile import NamedTemporaryFile

text = "mov9 = "   # if any line contains this text, I want to modify the whole line.
new_text = "mov9 = Alice in Wonderland\n"

with open("C:\Users\Admin\Desktop\DeletedMovies.txt") as f, NamedTemporaryFile("w", dir=".", delete=False) as tmp:
    for line in f:
        if text in line:
            line = new_text
        tmp.write(line)


move(tmp.name, "C:\Users\Admin\Desktop\DeletedMovies.txt")

As vyscond suggested:正如vyscond建议的那样:

import re
yourTxt = ''.join(open('file.txt').readlines())
yourTxt = re.sub(r'\bmov9\b', r'mov9 = Alice in Wonderland', yourTxt)

#Save the new text on disk
f = open('newTxt.txt', 'w')
f.write(yourTxt)
f.close()

I would suggest use two file simultaneously to replace the text and write the replaced data in another file and simply delete the older file.我建议同时使用两个文件来替换文本并将替换的数据写入另一个文件,然后简单地删除旧文件。

path="Hello.txt"
path2="Hello2.txt"
file1_open=open(path,"r") 
file2_open=open(path2,"w")
for line in file1_open:
if "a" in line:
print "found"
    line=line.replace('a',"replaced")
print line
    file2_open.write(line)

Now you can internally delete the file1_open file.现在您可以在内部删除 file1_open 文件。 It's small and simple though may take load on CPU when with large files.它小巧而简单,但在处理大文件时可能会对 CPU 造成负载。

It looks like this may not be the only solution on this theme, now that I have re-read the answers but as I knocked the code up here goes.看起来这可能不是这个主题的唯一解决方案,现在我已经重新阅读了答案,但是当我敲代码时,这里就开始了。 Keep it simple:把事情简单化:

import os
text = "mov9 = "   # if any line contains this text, I want to modify the whole line.
new_text = "mov9 = Alice in Wonderland "
new=open("new.txt",'w')
with open('DeletedMovies.txt', 'r') as f:
    for line in f.readlines():
        if text in line:
            line = line.replace(text, new_text)
            print line
        new.write(line)
new.close()
os.rename('DeletedMovies.txt', 'DeletedMovies.txt.old')
os.rename('new.txt', 'DeletedMovies.txt')

It rather depends on just how big you expect this file to get.这取决于您希望这个文件有多大。

Edit: If you are determined to use fileinput despite the the fact that it will be confusing for anyone unfamiliar with that package, as it is not at all clear what is happening, then you were almost there with your existing code.编辑:如果您决定使用fileinput ,尽管它会让不熟悉该包的任何人感到困惑,因为根本不清楚发生了什么,那么您几乎可以使用现有代码了。
The following should work:以下应该工作:

import fileinput
text = "mov9 = "   # if any line contains this text, I want to modify the whole line.
new_text = "mov9 = Alice in Wonderland "

for line in fileinput.input("DeletedMovies.txt", inplace = 1):
    if text in line:
        print line.replace(line,new_text)
    else:
        print line.strip()

With a slight improvement to the Rolf of Saxony answer, this you can run the script without having to hard coded values.通过对Rolf of Saxony 的答案稍作改进,您可以运行脚本而无需硬编码值。

import fileinput
import sys

filename=sys.argv[1]
old_value=sys.argv[2]
new_value=sys.argv[3]

with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
    for line in file:
        if old_value in line:
            print(line.replace(line,new_value))
        else:
            print(line.strip())

Now run it as replace.py filename.txt old_value New_Value from the command line现在从命令行将其作为replace.py filename.txt old_value New_Value运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM