Working with Files in Python
Working with files in Python is straightforward and can be done using built-in functions. Here’s a quick overview of the basic operations:
1. Opening a File
You can open a file using the open()
function. The syntax is:
file = open("filename.txt", "mode")
"mode"
specifies the mode in which the file is opened. Common modes are:"r"
: Read (default mode)"w"
: Write (creates a new file or truncates an existing one)"a"
: Append (writes to the end of the file)"b"
: Binary mode (e.g.,"rb"
or"wb"
for reading or writing binary files)"+"
: Updating (reading and writing)
Example:
file = open("example.txt", "r")
2. Reading from a File
You can read the contents of a file using various methods:
read()
: Reads the entire file.readline()
: Reads one line at a time.readlines()
: Reads all lines and returns them as a list.
Example:
content = file.read() # Reads the whole file
first_line = file.readline() # Reads the first line
all_lines = file.readlines() # Reads all lines into a list
Alternatively:
for line in file:
print(line)
3. Writing to a File
You can write to a file using the write()
or writelines()
methods.
write()
: Writes a string to the file.writelines()
: Writes a list of strings to the file.
Example:
file = open("example.txt", "w")
file.write("Hello, World!\n")
file.writelines(["Line 1\n", "Line 2\n"])
4. Closing a File
It’s important to close the file after you’re done with it to free up resources.
file.close()
Alternatively, you can use a with
statement to automatically close the file:
with open("example.txt", "r") as file:
content = file.read()
5. Working with Binary Files
For binary files, use "rb"
or "wb"
mode.
Example:
with open("image.jpg", "rb") as file:
data = file.read()
6. Checking if a File Exists
You can check if a file exists using the os.path
module:
import os
if os.path.exists("example.txt"):
print("File exists")
7. Deleting a File
To delete a file, you can use os.remove()
:
os.remove("example.txt")
8. Working with Paths
The os
and pathlib
modules help with file path operations:
os.path
: For basic path manipulations.pathlib.Path
: For a more modern and flexible approach.
Example using pathlib
:
from pathlib import Path
path = Path("example.txt")
if path.exists():
print(f"{path.name} exists")
These basics should cover most of your file operations in Python.
Last updated
Was this helpful?