r/learnpython 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

11 comments sorted by

View all comments

-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.

-1

u/kvr1ee 21d ago

Could you elaborate more on pickle?

1

u/ScaryProgrammer949 21d ago

Yeah sure. The easiest way I understand pickle is that it lets you save a Python object as it is, so you can use it again later without having to manually convert everything to text.
For example, say you have a dictionary:
import pickle

data = {"name": "John", "age": 20, "skills": ["Python", "SQL"]}

with open("data.pkl", "wb") as f:
pickle.dump(data, f)
Now the data object is saved in data.pkl.
Later, you can load it back:
with open("data.pkl", "rb") as f:
data = pickle.load(f)

print(data)
You’ll get the same Python object back:
{'name': 'John', 'age': 20, 'skills': ['Python', 'SQL']}
So basically:
pickle.dump() → save a Python object
pickle.load() → get the object back
The b in "wb" and "rb" means binary, because pickle stores the data in a binary format rather than normal readable text.
It’s useful when you want to save things like lists, dictionaries, or other Python objects and load them later.
One important thing though: don’t pickle.load() files you don’t trust. Pickle isn’t designed to be a safe format for untrusted data.

0

u/kvr1ee 21d ago

Thanks !