How to Read and Write Files in Python#
This guide explains how to read and write files in Python.
It is organized around the most commonly used example codes.
1. Reading a Text File - Reading the Entire File#
You can create a file stream using open("abcd.txt", "r") and read the entire file at once with .read().
(Creating a file stream means establishing a link to access the file.)
Here, "abcd.txt" refers to the full path of the file to be read, and you can use either an absolute path or a relative path."r" stands for read mode.
with open("abcd.txt", "r") as f:
content = f.read()
print(content)The above code uses the with statement, so the file stream is automatically released at the end of the with block.
Therefore, there is no need to use .close().
2. Reading a Text File - Reading Line by Line#
.readlines() reads the file line by line, using newline characters (’\n’) as separators, and returns a list.
Therefore, an example value of lines could be ['line 1\n', 'line 2\n', 'line 3'].
with open("abcd.txt", "r") as f:
lines = f.readlines()
print(lines)If you need to process the file line by line, you can write the code as follows:
with open("abcd.txt", "r") as f:
lines = f.readlines()
for line in lines:
print(line)3. Reading a Binary File#
You can read a binary file by setting the read mode to "rb" and using .read() to read the file.
Reading in binary mode means that you are reading the raw data of the file as it is.
For files other than text files, it is common to read them in binary mode.
with open("abcd.png", "rb") as f:
bin = f.read()
print(bin)4. Writing to a New File / Overwriting an Existing File#
The following code opens the file "aaaa.txt" in "w" (= write mode) and writes values using .write().
If the file ‘aaaa.txt’ exists, it will be overwritten; if it does not exist, a new file will be created.
with open("aaaa.txt", "w") as f:
f.write('hello world!')To write multiple lines, you can write the code as follows:
data = ['line1', 'line2', 'line3']
with open("aaaa.txt", "w") as f:
for line in data:
f.write(line + '\n')5. Appending to an Existing File#
The following code opens the file "aaaa.txt" in "a" (= append mode) and appends values using .write().
with open("aaaa.txt", "a") as f:
f.write('hello world!\n')6. Writing to a Binary File#
Set the read mode to "wb" and save as a binary file using .write().
with open("abcd.png", "wb") as f:
bin = f.write(b'\x01\x02')