簡體   English   中英

Python搜索和替換行

[英]Python Search and Replace Line

因此,我無法找到解決問題的方法。 我是Python的新手,似乎找不到找到實現此目的的方法。 我想做的是遍歷文件中的所有行,並針對每行匹配多個不同的規則,並用用戶內容替換整行。 我嘗試了多種方法,但是沒有一種方法可以滿足我的需求。

print ("File to perform check on:")

fileToSearch  = input( "> " )

for line in fileinput.input(fileToSearch, inplace=True):

    if 'foo' in line :

        if 'footimestwo' in line :

            sys.__stdout__.write('Wrong Answer. Try again:\n')

            textToReplace = input("")

            print(line.replace(line, textToReplace), end='')

這將用用戶輸入替換行,但不會保留行。 它只是用新行替換文件。

我嘗試的另一種方法是:

print ("File to perform check on:")

fileToSearch  = input( "> " )

fin = open(fileToSearch, 'r') 

fout = open("newFile.txt", 'w') 

for line in fin:

    if 'foo' in line :

        if 'rom' in line :

            print ('Wrong Answer. Try again:')

            textToReplace = input( "> ")

            fout.write(textToReplace+'\n')

        else: 

            fout.write(line)
    else:

        fout.write(line)

for line in fin:

    if 'ram' in line :

        if 'foo' in line :

            print ('Wrong Answer. Try again:')

            textToReplace = input( "> ")

            fout.write(textToReplace+'\n')

        else: 

            fout.write(line)

    else:

        fout.write(line)

fin.close()

fout.close()

這將在新文件中進行更改,並保留第一條語句的其余行的狀態,但不執行后續語句。 有任何想法嗎?

關於您的第一個代碼段,對於if 'footimestwo' in line:沒有else條件if 'footimestwo' in line:if 'foo' in line : if 'footimestwo' in line:沒有else條件,因此您只輸出要求用戶更正的行。

關於第二段代碼,對於一個小文件,最好將文件的各行存儲在內存中:

smallFile = open('path/to/a/small/file.txt')
lines = smallFile.readlines()
for i in range(0, len(lines)):
    #do things, but replace lines by doing:
    lines[i] = newStuffForLine

另外,您需要重置文件光標:

bigFile = open('path/to/a/big/file.txt')
outputIntermediate = open('path/to/a/tmp/file.txt', 'w')
for line in bigFile:
     #do first set of things, putting outputs in outputIntermediate
outputIntermediate.close()
bigFile.close()
bigFile = open('oath/to/a/tmp/file.txt')
for line in bigFile:
    #do second set of things

在第二個示例中,通過使用中間文件,可以防止在注釋中描述的問題,因為該問題僅是編輯相同的行集。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM