It's about reading Python file names, but I don't think I can even read them

Asked 1 years ago, Updated 1 years ago, 284 views

file_name = input ("Enter the file name:")
word_name = input ("Enter an existing word :")
new_word_name = input ("Enter a new word: ")

try :
    with open(file_name, "r") as f:
        lines = f.readline()
exceptionException aserr: //Error output when file does not exist
    print(str(err))

with open(file_name, "w") as f :
    for line in lines:
        if word_name in line :
            f.write(line.replace(word_name, new_word_name))
        print(line)`

Also, we made sample.txt in the same file and checked it with os.listdir('./').

In the terminal window,

sample.txt
123
xxx

I typed in and it ends with no output value. Let me know what the problem is.

python file

2022-10-13 01:00

1 Answers

The problem is that lines are not arrays.
Please try f.readlines().


2022-10-13 01:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.