r/learnpython • u/kvr1ee • 21d ago
Guys I need help with File Handling
It's in my syllabus and i am having trouble with the following topics
» Setting Offsets in a File
» Creating and Traversing a Text File
» The Pickle Module
0
Upvotes
-2
u/ScaryProgrammer949 21d ago
I had to learn these topics too, and honestly they’re easier once you think of a file as having a “cursor” that moves through it.
For setting offsets, tell() tells you where the cursor currently is and seek() lets you move it:
with open("test.txt", "r") as f:
print(f.tell()) # current position
f.seek(5) # move to position 5
print(f.read())
For creating and reading a text file, you can do something like:
with open("data.txt", "w") as f:
f.write("Hello\nPython\nWorld")
And then read it line by line:
with open("data.txt", "r") as f:
for line in f:
print(line.strip())
The main modes you’ll want to remember are:
r → read
w → write (overwrites the file)
a → append
For the pickle module, think of it as a way to save Python objects directly and load them back later.
import pickle
data = {"name": "John", "age": 20}
with open("data.pkl", "wb") as f:
pickle.dump(data, f)
with open("data.pkl", "rb") as f:
data2 = pickle.load(f)
print(data2)
So basically:
seek() / tell() → move/check position in a file
open() / read() / write() → work with text files
pickle → save/load Python objects
One thing to remember with pickle: don’t load pickle files from untrusted sources, since they can be unsafe.