Introduction to Files
A file is a container in a computer system used to store data permanently. Files allow us to store data for future
use and share it between programs.
Types of Files
1. Text File: Stores data in a readable text format. E.g., .txt files.
2. Binary File: Stores data in binary format, not human-readable. E.g., images, .exe files.
3. CSV File: A text file where data is stored in tabular form using commas as delimiters. E.g., .csv.
Text File Operations
Opening a Text File
Use the open() function.
Syntax:
python
Copy code
file = open("filename.txt", mode)
Modes:
• r: Read-only.
• r+: Read and write.
• w: Write-only (overwrites file).
• w+: Write and read (overwrites file).
• a: Append.
• a+: Append and read.
Example:
python
Copy code
file = open("example.txt", "w") # Opens file in write mode
file.write("Hello, world!") # Writes to the file
file.close() # Closes the file
Using with Clause
Automatically closes the file after operations.
Syntax:
python
Copy code
with open("filename.txt", mode) as file:
# file operations
Example:
python
Copy code
with open("example.txt", "a") as file:
file.write("\nAppending new line.")
Writing to a Text File
• write(): Writes a single string to the file.
• writelines(): Writes multiple strings (list/iterable) to the file.
Example:
python
Copy code
with open("example.txt", "w") as file:
file.write("First line.\n")
file.writelines(["Second line.\n", "Third line.\n"])
Reading from a Text File
• read(): Reads the entire file content as a string.
• readline(): Reads one line at a time.
• readlines(): Reads all lines and returns a list.
Example:
python
Copy code
with open("example.txt", "r") as file:
print(file.read()) # Read entire file
file.seek(0) # Move pointer to the beginning
print(file.readline()) # Read first line
print(file.readlines()) # Read all lines as a list
Complete Example Program
python
Copy code
# Writing data to a file
with open("example.txt", "w") as file:
file.write("Python File Handling Example\n")
file.writelines(["Line 1\n", "Line 2\n", "Line 3\n"])
# Appending data
with open("example.txt", "a") as file:
file.write("Appending this line.\n")
# Reading data
with open("example.txt", "r") as file:
print("File Content Using read():")
print(file.read())
file.seek(0)
print("\nFile Content Using readline():")
print(file.readline(), end="")
print(file.readline(), end="")
file.seek(0)
print("\nFile Content Using readlines():")
print(file.readlines())
Output:
mathematica
Copy code
File Content Using read():
Python File Handling Example
Line 1
Line 2
Line 3
Appending this line.
File Content Using readline():
Python File Handling Example
Line 1
File Content Using readlines():
['Python File Handling Example\n', 'Line 1\n', 'Line 2\n', 'Line 3\n', 'Appending this line.\n']
File Handling in Python with Libraries
Python provides a robust set of libraries to simplify file operations, such as working with text, binary, and CSV
files. Here's an in-depth explanation.
Core Libraries for File Handling
1. os: For working with file paths and directories.
2. shutil: For file copying and moving.
3. csv: For reading and writing CSV files.
4. pandas: For advanced CSV/Excel file handling.
5. pickle: For binary file handling with serialized data.
Detailed Topics
Text File Handling
Text files are commonly used for storing plain data, such as logs or reports.
Opening and Closing a File
Use the open() function to open a file and specify the mode:
python
Copy code
import os
# Opening a file
file = open("example.txt", "w") # 'w' mode opens the file for writing
file.write("This is an example text file.\n")
file.close()
# Check if the file exists
print(os.path.exists("example.txt")) # Output: True
Using with Clause
The with clause ensures the file is automatically closed.
python
Copy code
with open("example.txt", "a") as file:
file.write("This is an appended line.\n")
Reading File Content
Python offers multiple methods for reading file content:
• read(): Reads the entire file.
• readline(): Reads one line at a time.
• readlines(): Reads all lines and returns a list.
Example:
with open("example.txt", "r") as file:
print(file.read()) # Reads entire file
file.seek(0) # Move the pointer to the start
print(file.readline()) # Reads the first line
print(file.readlines()) # Returns a list of lines
CSV File Handling
CSV files store data in tabular form. Python provides two libraries for handling CSV files:
1. csv Module (built-in)
2. pandas (third-party library for advanced operations)
Using csv Module
python
Copy code
import csv
# Writing to a CSV file
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "City"])
writer.writerows([["Alice", 30, "New York"], ["Bob", 25, "Los Angeles"]])
# Reading from a CSV file
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Using pandas
python
Copy code
import pandas as pd
# Writing to a CSV file
data = {"Name": ["Alice", "Bob"], "Age": [30, 25], "City": ["New York", "Los Angeles"]}
df = pd.DataFrame(data)
df.to_csv("data.csv", index=False)
# Reading from a CSV file
df = pd.read_csv("data.csv")
print(df)
Binary File Handling
Binary files store data in binary (0s and 1s) format, commonly used for images, videos, or serialized objects.
Using pickle Module
python
Copy code
import pickle
# Writing to a binary file
data = {"Name": "Alice", "Age": 30, "City": "New York"}
with open("data.pkl", "wb") as file:
pickle.dump(data, file)
# Reading from a binary file
with open("data.pkl", "rb") as file:
loaded_data = pickle.load(file)
print(loaded_data)
Working with os and shutil
These libraries help in managing files and directories.
File Operations
python
Copy code
import os
import shutil
# Check if file exists
if os.path.exists("example.txt"):
print("File exists")
# Rename a file
os.rename("example.txt", "new_example.txt")
# Copy a file
shutil.copy("new_example.txt", "copied_example.txt")
# Delete a file
os.remove("new_example.txt")
Advanced Examples
Program: Combine Text File Content
python
Copy code
import os
# Combine multiple text files
files = ["file1.txt", "file2.txt", "file3.txt"]
with open("combined.txt", "w") as outfile:
for fname in files:
if os.path.exists(fname):
with open(fname, "r") as infile:
outfile.write(infile.read())
Program: Search in a CSV File
python
Copy code
import csv
# Search for a specific value in CSV
with open("data.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
if row["Name"] == "Alice":
print(f"Found: {row}")