Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

File Handling in Python – Code Snippets
Opening Files
with open('example.txt', 'r') as file:
content = file.read()
File Access Methods
file.read()
file.readline()
file.readlines()
Writing Data to a File
with open('example.txt', 'w') as file:
file.write('Hello, World!')
Binary Files
with open('example.bin', 'wb') as file:
file.write(b'Binary data')
Pickling and Unpickling
import pickle
data = {'key': 'value'}
with open('data.pkl', 'wb') as file:
pickle.dump(data, file)
with open('data.pkl', 'rb') as file:
loaded_data = pickle.load(file)
Using the seek()
and tell()
Methods
with open(
File Handling in Python - Code Snippets
Opening Files
with open('example.txt', 'r') as file:
content = file.read()
File Access Methods
file.read()
file.readline()
file.readlines()
Writing Data to a File
with open('example.txt', 'w') as file:
file.write('Hello, World!')
Binary Files
with open('example.bin', 'wb') as file:
file.write(b'Binary data')
Pickling and Unpickling
import pickle
data = {'key': 'value'}
with open('data.pkl', 'wb') as file:
pickle.dump(data, file)
with open('data.pkl', 'rb') as file:
loaded_data = pickle.load(file)
Using the seek()
and tell()
Methods
with open('example.txt', 'r') as file:
file.seek(5)
position = file.tell()
Reading and Writing CSV Files
import csv
with open('example.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age'])
writer.writerow(['John', '25'])
with open('example.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
xt', 'r') as file:
file.seek(5)
position = file.tell()
Reading and Writing CSV Files
import csv
with open('example.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age'])
writer.writerow(['John', '25'])
with open('example.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)