Python provides several ways to manipulate files. Today, we will discuss how to handle files in Python.
Before we can perform any operations on a file, we must first open it. Python provides the open() function to open a file. It takes two arguments: the name of the file and the mode in which the file should be opened. The mode can be 'r' for reading, 'w' for writing, or 'a' for appending.
Here's an example of how to open a file for reading:
f = open('myfile.txt', 'r')
By default, the open() function returns a file object that can be used to read from or write to the file, depending on the mode.
There are various modes in which we can open files.
Once we have a file object, we can use various methods to read from the file.
f = open('myfile.txt', 'r')
contents = f.read()
print(contents)
To write to a file, we first need to open it in write mode.
f = open('myfile.txt', 'w')
We can then use the write() method to write to the file.
f = open('myfile.txt', 'w')
f.write('Hello, world!')
Keep in mind that writing to a file will overwrite its contents. If you want to append to a file instead of overwriting it, you can open it in append mode.
f = open('myfile.txt', 'a')
f.write('Hello, world!')
f.close()
If we run a loop, file won't be overwritten until the loop finishes. Like:
f = open('myfile.txt', 'w')
lines = ['line 1', 'line 2', 'line 3']
lines = ['line 1', 'line 2', 'line 3']
for line in lines:
f.write(line + '\n')
f.close()
# Output in myfile.txt:
line 1
line 2
line 3
It is important to close a file after you are done with it. This releases the resources used by the file and allows other programs to access it.
To close a file, you can use the close() method.
f = open('myfile.txt', 'r')
# ... do something with the file
f.close()
Alternatively, you can use the with statement to automatically close the file after you are done with it.
with open('myfile.txt', 'r') as f:
# ... do something with the file