How to Read, Write, and Modify Text Files in Python Using open()
This tutorial walks through creating a Python script that opens a text file, reads its contents, prints them, then demonstrates how to overwrite the file with new text, explaining each step, the importance of closing files, and additional file‑operation commands such as readline, truncate, and write.
This section works with two files placed in the same directory: the existing first.py script and a new second.txt file. The second.txt file initially contains a single line: hello!I am txt. The goal is to read and display this line from Python, even though the string does not exist in the script itself.
First, the following code is executed:
txt = open("second.txt", "r")
content = txt.read()
print(content)
txt.close()The code opens the file with open(), reads its entire content using read(), prints the content, and finally closes the file. Closing the file is emphasized because an open handle prevents other programs from modifying the file.
Additional file‑operation keywords are introduced:
readline – reads a single line from the file.
truncate – clears the file’s contents (use with caution).
write(stuff) – writes the string stuff to the file.
Next, the tutorial shows how to modify second.txt by overwriting it:
txt = open("second.txt", "w")
txt.write("this is python write!")
txt.close()After running this code, the file’s content becomes exactly this is python write!. The author notes that if the original content should be preserved, one must first read the existing data, append a newline, and then write the combined text back.
The lesson concludes by encouraging readers to experiment with these basic file‑handling commands, noting that mastering them completes the Python fundamentals covered so far.
AI Large-Model Wave and Transformation Guide
Focuses on the latest large-model trends, applications, technical architectures, and related information.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
