File Handling
🗂️ Python File Handling — Q & A (with code)
Q1: How do you read a file line-by-line safely in Python?
A:
with open('data.txt', 'r') as f:
for line in f:
print(line.strip())
Q2: How do you write a list of lines to a file in Python?
A:
lines = ['one\n', 'two\n', 'three\n']
with open('output.txt', 'w') as f:
f.writelines(lines)
Q3: How do you check if a file exists before opening it?
A:
import os
if os.path.exists('file.txt'):
with open('file.txt') as f:
print(f.read())
Q4: How do you list all files in a folder with a .txt
extension?
A:
import os
files = [f for f in os.listdir('my_folder') if f.endswith('.txt')]
print(files)
Q5: How do you recursively list all .jpg
files in a directory and its subdirectories?
A:
import os
jpgs = []
for root, dirs, files in os.walk('assets'):
for f in files:
if f.endswith('.jpg'):
jpgs.append(os.path.join(root, f))
Q6: How do you create a folder if it doesn’t exist?
A:
import os
os.makedirs('my_folder', exist_ok=True)
Q7: How do you read and write JSON data using Python?
A:
import json
# Writing
data = {'name': 'Alice', 'age': 30}
with open('data.json', 'w') as f:
json.dump(data, f, indent=4)
# Reading
with open('data.json') as f:
loaded = json.load(f)
Q8: How do you move or rename a file?
A:
import shutil
shutil.move('old_name.txt', 'new_folder/new_name.txt')
Q9: How do you delete a file safely in Python?
A:
import os
if os.path.exists('to_delete.txt'):
os.remove('to_delete.txt')
Q10: How do you get the filename and extension separately?
A:
import os
path = '/path/to/file.jpg'
name, ext = os.path.splitext(os.path.basename(path))
print(name) # file
print(ext) # .jpg
Ready for me to export this as a .csv
for Anki?
No Comments