Use the built-in open()
function:
file = open('filename.txt', mode)
'filename.txt'
is the file name (and path if not in the current directory).
mode
is the mode in which you open the file. Common modes:
'r'
— read (default)
'w'
— write (creates or truncates file)
'a'
— append (write data to the end)
'b'
— binary mode (used with other modes, like 'rb'
or 'wb'
)
'x'
— create a new file and open it for writing (error if exists)
'+'
— read and write (e.g., 'r+'
, 'w+'
)
Read whole file:
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
Read line by line:
file = open('example.txt', 'r')
for line in file:
print(line.strip()) # strip removes trailing newline
file.close()
Read a single line:
file = open('example.txt', 'r')
line = file.readline()
print(line)
file.close()
Read lines as list:
file = open('example.txt', 'r')
lines = file.readlines()
print(lines)
file.close()
Overwrite or create file and write:
file = open('example.txt', 'w')
file.write("Hello, world!\n")
file.write("Welcome to file operations in Python.\n")
file.close()
Append to a file:
file = open('example.txt', 'a')
file.write("This will be added at the end.\n")
file.close()
After file operations, always close the file to free resources:
file.close()
with
Statement (Recommended)Using with
automatically closes the file when the block is exited, even if an error occurs.
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# No need to call file.close()
Check if file exists:
import os
if os.path.exists('example.txt'):
print("File exists")
else:
print("File does not exist")
Rename or delete file:
import os
os.rename('old.txt', 'new.txt')
os.remove('example.txt')
Mode | Description |
---|---|
'r' |
Read (default) |
'w' |
Write (overwrite or create) |
'a' |
Append to file |
'x' |
Create new file (fail if exists) |
'b' |
Binary mode |
'+' |
Read and write |