Working with Files in Python
⏱ Estimated reading time: 2 min
Working with Files in Python
Python allows you to create, read, write, and manipulate files using built-in functions. Files can be text files or binary files.
Opening a file:
Use the open() function with the file name and mode.
Example:
file = open("example.txt", "r") # open file in read mode
File modes:
-
"r"→ read (default), file must exist -
"w"→ write, creates file or overwrites if exists -
"a"→ append, adds content to the end -
"x"→ create, fails if file exists -
"b"→ binary mode -
"t"→ text mode (default) -
"+"→ read and write
Reading from a file:
-
read(): reads entire content -
read(size): reads specified number of characters -
readline(): reads one line -
readlines(): reads all lines into a list
Example:
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
Writing to a file:
-
write(string): writes a string to the file -
writelines(list_of_strings): writes a list of strings
Example:
file = open("example.txt", "w")
file.write("Hello Python\n")
file.writelines(["Line 1\n", "Line 2\n"])
file.close()
Appending to a file:
Example:
file = open("example.txt", "a")
file.write("This is appended text\n")
file.close()
Closing a file:
Always close a file to free system resources.
Example:
file.close()
Using with statement:
Automatically handles closing the file.
Example:
with open("example.txt", "r") as file:
content = file.read()
print(content)
Checking if a file exists (optional):
Use the os module.
Example:
import os
if os.path.exists("example.txt"):
print("File exists")
else:
print("File does not exist")
File pointer methods:
-
tell(): returns current position -
seek(position): moves pointer to specified position
Reading large files efficiently:
Use a loop to read line by line.
Example:
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
Register Now
Share this Post
← Back to Tutorials