繁体   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