File Handling in Python
Manage files and directories in Python
File handling in Python allows you to work with files—reading, writing, appending, and managing data stored in files. Python provides built-in functions and methods for file handling, making it easy to manage files and directories.
Basics of File Handling
-
Opening a File
Use theopen()
function to open a file.file = open("filename", mode)
filename
: Name or path of the file.mode
: Specifies the mode for file operations:'r'
: Read (default).'w'
: Write (creates/overwrites the file).'a'
: Append (adds to the file if it exists).'x'
: Create (fails if the file exists).'b'
: Binary mode (e.g.,'rb'
,'wb'
).'t'
: Text mode (default, e.g.,'rt'
).
-
Closing a File
Always close files after use to release resources:file.close()
-
Using
with
Statement
Thewith
statement ensures files are properly closed after their block of code is executed:with open("filename", "mode") as file: # Perform file operations
Common File Operations
- Reading from a File
# Read the entire file
with open("example.txt", "r") as file:
content = file.read()
print(content)
# Read line by line
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
- Writing to a File
# Write to a new or existing file (overwrites content)
with open("example.txt", "w") as file:
file.write("This is a new line.\n")
file.write("Another line.\n")
- Appending to a File
# Add content to an existing file
with open("example.txt", "a") as file:
file.write("This line is appended.\n")
File Methods
read(size)
: Readssize
characters or bytes (default is the entire file).readline()
: Reads a single line from the file.readlines()
: Reads all lines as a list.write(string)
: Writes a string to the file.writelines(lines)
: Writes a list of strings to the file.
Copying Content from One File to Another
with open("source.txt", "r") as source:
content = source.read()
with open("destination.txt", "w") as destination:
destination.write(content)
Checking File Existence
Use the os
module to check if a file exists:
import os
if os.path.exists("example.txt"):
print("File exists.")
else:
print("File does not exist.")
Modes Summary
Mode | Description |
---|---|
'r' | Read (default, file must exist) |
'w' | Write (create/overwrite file) |
'a' | Append (add to existing file) |
'x' | Create (fail if file exists) |
'b' | Binary mode (e.g., 'rb' ) |
't' | Text mode (default, e.g., 'rt' ) |
No questions available.