#4 – File Handling Flashcards
(15 cards)
How do you open a file for reading?
Use open()
with mode 'r'
.
~~~
with open(‘file.txt’, ‘r’) as f:
content = f.read()
~~~
How do you read a file line by line?
Use .readlines()
or loop over the file object.
~~~
with open(‘file.txt’) as f:
for line in f:
print(line)
~~~
How do you write to a file (overwrite)?
Use mode 'w'
.
~~~
with open(‘file.txt’, ‘w’) as f:
f.write(‘Hello’)
~~~
How do you append to a file?
Use mode 'a'
.
~~~
with open(‘file.txt’, ‘a’) as f:
f.write(‘More text’)
~~~
How do you open a file in binary mode?
Add 'b'
to the mode, e.g., 'rb'
, 'wb'
.
~~~
with open(‘image.jpg’, ‘rb’) as f:
data = f.read()
~~~
What does with open(...)
do?
It ensures the file is closed automatically after the block finishes, even if an error occurs.
How do you check if a file exists before opening it?
Use the os.path.exists()
function.
~~~
import os if os.path.exists(‘file.txt’):
with open(‘file.txt’) as f:
…
~~~
How do you handle file-related errors safely?
Use a try-except
block.
~~~
try:
with open(‘file.txt’) as f:
… except FileNotFoundError:
print(‘File not found’)
~~~
How do you read and write JSON data?
Use the json
module.
~~~
import json with open(‘data.json’) as f:
data = json.load(f) with open(‘out.json’, ‘w’) as f:
json.dump(data, f)
~~~
How do you convert a Python object to a JSON string?
Use json.dumps()
.
~~~
json.dumps({‘a’: 1}) # returns: ‘{“a”: 1}’
~~~
How do you parse a JSON string into a Python object?
Use json.loads()
.
~~~
json.loads(‘{“a”: 1}’)
# returns: {‘a’: 1}
~~~
How do you move or rename a file?
Use os.rename()
.
~~~
import os os.rename(‘old.txt’, ‘new.txt’)
~~~
How do you delete a file?
Use os.remove()
.
~~~
import os os.remove(‘file.txt’)
~~~
How do you read only the first N bytes from a file?
Use .read(n)
.
~~~
with open(‘file.txt’) as f:
data = f.read(10)
~~~
How do you flush a file buffer manually?
Call f.flush()
.
~~~
f = open(‘file.txt’, ‘w’)
f.write(‘Hi’)
f.flush()
~~~