Modifying and saving Python text files

Asked 1 years ago, Updated 1 years ago, 99 views

If you use the open() function in Python, you can read, write, and add text files What I want is to modify the existing file and save it right away.

First of all, I'll give you a quick example of what I'm curious about.

When the above txt file exists, read the file first, and then

f = open ("C:/Users/YEONGHUN/Desktop/test.txt", 'r')
file = f.read()
f.close()

I made a list of the contents of the test file, and when I found the number 7 in the for statement, I changed it to 0 and saved the test file immediately, so I wrote the code as below.

(Of course, I know that if you use the write function as an open function, it will be zero after deleting the contents of the file, but there is nothing to show you as a good example, so I wrote the idea in code.))

list = file.splitlines()

print(list)
for line in list:
    print(line)
    if line == '7':
        g = open("C:/Users/YEONGHUN/Desktop/test.txt", 'w+')
        new = g.write("0")

        g.close()

The key is if there is a basic source that can modify and save the desired part of the existing file using the for and if statements, please give us your opinions.

python text-file save savetxt

2022-09-20 22:19

1 Answers

The file object has a method called seek.

Open the file (r+) and upload the contents to the memory (list, etc.), modify the contents of the memory, and then write the contents of the memory after setting the pointer for the first time.


2022-09-20 22:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.