Python File Reading and Writing (Text Files)
Page Info
Content
Python File Reading and Writing (Text Files)
In Python, you can read and write text files using the open()
function, ideally combined with a with
statement to ensure the file is properly closed. Use w
mode to write and r
mode to read files. Methods like read()
and readlines()
help process file content.
Writing to a File
# Open 'my_file.txt' in write mode (creates or overwrites the file)
with open("my_file.txt", "w", encoding="utf-8") as f:
f.write("This is the first line.\n")
f.write("This is the second line.")
# File is automatically closed after the with block
Explanation:
open("my_file.txt", "w", encoding="utf-8")
: Opens the file in write mode with UTF-8 encoding. Creates a new file or overwrites if it exists.f.write(...)
: Writes the specified string to the file. Use\n
for line breaks.with
ensures the file is automatically closed.
Reading from a File
# Read the entire file content
with open("my_file.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
# Read the file line by line into a list
with open("my_file.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
for line in lines:
print(line.strip()) # Remove leading/trailing whitespace and newline
Explanation:
open("my_file.txt", "r", encoding="utf-8")
: Opens the file in read mode with UTF-8 encoding.f.read()
: Reads the entire file as a single string.f.readlines()
: Reads all lines into a list.line.strip()
: Removes whitespace and newline characters from each line.
Key Points
- Always use
with
for automatic file closing. - Use
w
mode for writing,r
mode for reading. - Use
\n
to add line breaks when writing.
SEO Keywords
Python file read write, Python open() example, Python readlines, Python write text file, Python with statement file, Python text file operations
These methods allow you to efficiently read from and write to text files in Python while handling encoding and ensuring proper file closure.
Good0 Bad0
댓글목록
등록된 댓글이 없습니다.