Understanding how to read and write to files
Files are a common way to store and exchange data. Python provides built-in functions and methods to read from and write to files.
Opening a File
To work with a file, you first need to open it using the built-in open
function. This function returns a file object that you can use to read from or write to the file. Here is the syntax:
file = open("filename", "mode")
The filename
is a string that specifies the name of the file. The mode
is a string that specifies how you plan to use the file. Some common modes include:
"r"
for reading"w"
for writing (this will overwrite existing files)"a"
for appending (this will add to the end of existing files)"x"
for creating (this will create a new file and raise an error if the file exists)
Reading from a File
To read the entire content of a file as a single string, use the read
method:
file = open("example.txt", "r") content = file.read() print(content) file.close()
To read the content line by line, use the readlines
method:
file = open("example.txt", "r") lines = file.readlines() for line in lines: print(line) file.close()
Note: Always remember to close the file after you’re done using it, by calling the close
method. This is important to free up system resources.
Writing to a File
To write to a file, open it in "w"
or "a"
mode, and then use the write
method:
file = open("example.txt", "w") file.write("Hello, world!") file.close()
This will replace the content of example.txt
with the string "Hello, world!"
.
Using with
Statements
To automatically close a file after you’re done using it, you can open it using a with
statement:
with open("example.txt", "r") as file: print(file.read())
In this code, file.close()
is called automatically at the end of the with
block.
In conclusion, Python’s file reading and writing capabilities make it a powerful tool for working with data stored in files. With these basic operations, you can accomplish a wide range of tasks.