简体   繁体   English

替换Python 3中的文本,但只能读取一行

[英]Replacing text in Python 3 but its reading only one line

I am trying to use search and replace in Python 3 with file 我正在尝试使用搜索并在Python 3中用文件替换

but when i try my code it only works on the first line and don't go through each and every line and replace it. 但是当我尝试我的代码时,它仅在第一行起作用,而不是遍历每一行并替换它。

What i am trying so far 到目前为止我正在尝试

f1 = open('test.txt', 'r')
f2 = open('test2.txt', 'w')
for line in f1:
    f1.readlines()
    find = (input('Enter word to find: '))
    while find in line:
        print('Word Found')
        replace = input('Enter Word to replace with: ')
        replace_action = (input('Are you sure you want to replace Y or N:'))
        if replace_action.lower() == 'y':
            f2.write(line.replace(find.lower(), replace))
        else:
            print('You have cancelled this operation')
    else:
        print('Word not found in file')
f1.close()
f2.close()

This code is only reading the first line but doesnot work further. 这段代码仅读取第一行,而不再起作用。

This is happening because you are not reading the file properly. 发生这种情况是因为您没有正确读取文件。

for line in f1:
    f1.readlines()

f1.readlines() consumes all the file lines returning a list of strings. f1.readlines()消耗所有文件行,并返回字符串列表。
You just need to remove the f1.readlines() line. 您只需要删除f1.readlines()行。

Check the documentation if you would like to know the various ways of reading a file in python. 如果您想了解以python读取文件的各种方式,请查阅文档。 https://docs.python.org/2.7/tutorial/inputoutput.html https://docs.python.org/2.7/tutorial/inputoutput.html
https://docs.python.org/3/tutorial/inputoutput.html https://docs.python.org/3/tutorial/inputoutput.html

f1 = open('test.txt', 'r')
f2 = open('test2.txt', 'w')

lines = f1.readlines()

find = (input('Enter word to find: '))
replace = input('Enter Word to replace with: ')
for line in lines:
    print('current line: {}'.format(line))

    if not find in line:
        print('world {} not found in this line. Moving to next line'.format(find))
        continue

    print('World {} found in this line'.format(find))

    replace_action = input('Are you sure you want to replace for this line y or n')

    if replace_action.lower() == 'y':
        line = line.replace(find.lower(), replace)
        f2.write(line)
        print("New line: {}".format(line))
    else:
        print('You have cancelled this operation')

    print("")

f1.close()
f2.close()

The method readlines() reads until EOF using readline() and returns a list containing the lines. 该方法readlines()读取直到EOF使用readline()并返回包含行的列表。

f1 = open('test.txt', 'r')
f2 = open('test2.txt', 'w')

f1_lines = f1.readlines()
f1.close()

for line in f1_lines:
    find = input('Enter word to find: ')
    if find in line:
        print('Word Found')
        replace = input('Enter Word to replace with: ')
        replace_action = input('Are you sure you want to replace Y or N:')
        if replace_action.lower() == 'y':
            f2.write(line.replace(find.lower(), replace))
        else:
            print('You have cancelled this operation')
    else:
        print('Word not found in file')
        f2.write(line)

f2.close()

I changed a few thinks based on what I understood of the question. 根据对问题的了解,我改变了一些想法。 if find in line checks if the input you look for is in the line. if find in line检查您要查找的输入是否在行中。 If it is, the line is written to f2 with the replace, else the line is written to f2 as it was. 如果是,则使用替换将行写入f2,否则将行直接写入f2。

EDIT: You got another issue I guess. 编辑:我猜你还有另一个问题。 Works for me. 为我工作。

runfile('C:/Users/mathieu.scheltienne/Desktop/test/untitled0.py', wdir='C:/Users/mathieu.scheltienne/Desktop/test')

Enter word to find: hello
Word Found

Enter Word to replace with: good bye

Are you sure you want to replace Y or N:y

Enter word to find: hello
Word Found

Enter Word to replace with: good bye

Are you sure you want to replace Y or N:y

Enter word to find: hello
Word Found

Enter Word to replace with: good bye

Are you sure you want to replace Y or N:y

Input file was: test.txt 输入文件为:test.txt

hello world
hello galaxy
hello universe

Output file: 输出文件:

good bye world
good bye galaxy
good bye universe

Version with only one word that is going to be replace by only one word on every line: 仅包含一个单词的版本,每行仅将替换为一个单词:

f1 = open('test.txt', 'r')
f2 = open('test2.txt', 'w')

f1_lines = f1.readlines()
f1.close()

find = input('Enter word to find: ')
replace = input('Enter Word to replace with: ')
counter = 0

for line in f1_lines:
    if find in line:
        print('Word Found')
        f2.write(line.replace(find.lower(), replace))
        counter += 1
    else:
        f2.write(line)

if counter == 0:
    print('Word not found in file')
else:
    print('{} words replaced'.format(counter))

f2.close()

I think you already have a solution, however there are few places where it can be optimized. 我认为您已经有了解决方案,但是很少有地方可以优化它。

  • Use python contextmanager with for handling files, then you dont need to worry about closing it. 使用python contextmanager with处理文件,那么您不必担心关闭它。 In your case the file will not be closed in case there is an exception thrown during for loop. 在您的情况下,如果在for循环期间抛出异常,则不会关闭文件。
  • Using with you dont need to call readline() . with您一起使用不需要调用readline()
  • Use try/catch block if you getting inputs from external source. 如果从外部来源获取输入,请使用try/catch块。

Here is another way of doing it. 这是另一种方法。

def  readfile_and_replace(input_filename, output_filename):
     #using python context manager to open file. File will be closed even in case of exception
     with open(input_filename) as input_file:
        with open(output_filename,'w') as output_file:
            try:
                for line in input_file:
                    search_str = (input('Enter word to find: '))
                    new_line = line
                    if search_str in line:
                        replace_str = input('Enter Word to replace with: ')
                        if input('Are you sure you want to replace Y or N:').upper() == 'Y':
                            new_line = line.replace(search_str.lower(), replace_str)
                            #print(line.replace(search_str.lower(), replace_str))
                        else:
                            print('You have cancelled this operation')
                    else :
                        print('Word not found in current line')

                    output_file.write(new_line)
            except KeyboardInterrupt:
                print("user aborted the program")


readfile_and_replace(input_filename='logs.txt', output_filename='logs2.txt') 

I hope it helps. 希望对您有所帮助。

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

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