📝 Working with Files¶
Let's go over the basics of working with files in Python. This will include opening, reading, writing, and closing files.
1. Opening a File¶
To open a file in Python, we use the open()
function. This function takes in the path to the file as a string and returns a file object.
file = open('my_file.txt')
By default, the open()
function opens the file in read mode. If you want to open the file in a different mode, you can specify this with a second string argument. For example, 'w' for write mode, 'r' for read mode, 'a' for append mode, and 'b' for binary mode.
file = open('my_file.txt', 'w')
2. Reading from a File¶
To read the entire contents of a file, you can use the read()
method of the file object.
file = open('my_file.txt', 'r')
content = file.read()
print(content)
file.close()
Hello, world!
If you want to read the file line by line, you can use the readlines()
method.
file = open('my_file.txt', 'r')
lines = file.readlines()
for line in lines:
print(line)
file.close()
Hello, world!
3. Writing to a File¶
To write to a file, you first need to open it in write ('w') or append ('a') mode. Then, you can use the write()
method.
file = open('my_file.txt', 'w')
file.write('Hello, world!')
file.close()
Keep in mind that opening a file in 'w' mode will erase all its contents. If you want to add to the existing contents of the file, you should open it in 'a' mode.
4. Closing a File¶
After you're done with a file, you should close it with the close()
method. This frees up system resources.
file = open('my_file.txt')
# Do stuff with file
file.close()
5. Using 'with' Statement¶
It's easy to forget to close a file. Therefore, it's a good practice to open files in a with
statement. This will automatically close the file when the with
block is exited.
with open('my_file.txt', 'r') as file:
print(file.read())
# The file is automatically closed here
Hello, world!
Working with files is a common task in programming, and Python provides an easy-to-use and flexible set of functions and methods for this purpose.