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

时间:2018-04-25 14:32:28

标签: python

我正在尝试使用Python 3中的搜索和替换文件

但是当我尝试我的代码时,它只适用于第一行,并且不会遍历每一行并替换它。

到目前为止我在尝试什么

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()

此代码仅读取第一行但不起作用。

4 个答案:

答案 0 :(得分:2)

这种情况正在发生,因为您没有正确阅读文件。

for line in f1:
    f1.readlines()

f1.readlines()使用返回字符串列表的所有文件行 您只需要删除f1.readlines()行。

如果您想了解在python中读取文件的各种方法,请查看文档。 https://docs.python.org/2.7/tutorial/inputoutput.html
https://docs.python.org/3/tutorial/inputoutput.html

答案 1 :(得分:2)

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()

答案 2 :(得分:1)

方法readlines()使用readline()读取EOF,并返回包含这些行的列表。

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()

我根据我对这个问题的理解改变了一些想法。 if find in line检查您查找的输入是否在行中。如果是,则使用replace将行写入f2,否则该行将按原样写入f2。

编辑:我猜你还有另一个问题。适合我。

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

输入文件是:test.txt

hello world
hello galaxy
hello universe

输出文件:

good bye world
good bye galaxy
good bye universe

只有一个单词的版本,每行只能替换一个单词:

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()

答案 3 :(得分:0)

我认为您已经有了解决方案,但是很少有地方可以对其进行优化。

  • 使用python contextmanager with 来处理文件,然后您不必担心关闭它。在您的情况下,如果在for循环期间抛出异常,则不会关闭该文件。
  • 使用with,您无需致电readline()
  • 如果您从外部来源获取输入,请使用try/catch阻止。

这是另一种方法。

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') 

我希望它有所帮助。