Reading and Writing Files in Python
In Python, reading from and writing to files are fundamental operations for file handling. Understanding how to properly read and write data is essential for any file manipulation task.
Reading from a File
To read from a file, you typically open it in read mode ('r')
and use methods like read()
, readline()
, or readlines()
to retrieve its content.
Example of Reading a File
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print(content)
Output
Writing to a File
To write to a file, you open it in write mode ('w')
or append mode ('a')
. The write()
method is used to add data to the file.
Example of Writing to a File
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, World!n")
file.write("Welcome to file handling in Python.n")
Output
Reading Lines from a File
You can also read the file line by line using readline()
or readlines()
. This is useful when dealing with large files.
Example of Reading Lines from a File
# Reading lines from a file
with open("example.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line.strip())
Output
Appending to a File
To add more content to an existing file without erasing its current content, use the append mode ('a')
.
Example of Appending to a File
# Appending to a file
with open("example.txt", "a") as file:
file.write("This line is added at the end of the file.n")
Output
Conclusion
Reading from and writing to files in Python is straightforward. Using the with
statement is a best practice, as it ensures that files are properly closed after their operations are completed. Understanding these basic file operations is essential for effective file handling in Python.