简体   繁体   中英

Replacing text in Python 3 but its reading only one line

I am trying to use search and replace in Python 3 with file

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.
You just need to remove the f1.readlines() line.

Check the documentation if you would like to know the various ways of reading a file in python. https://docs.python.org/2.7/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.

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 it is, the line is written to f2 with the replace, else the line is written to f2 as it was.

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

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. In your case the file will not be closed in case there is an exception thrown during for loop.
  • Using with you dont need to call readline() .
  • Use try/catch block if you getting inputs from external source.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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