Code snippet showing how to unpack strings.

File unpacking

After learning that strings can be unpacked in Python, I shared the short article on Twitter.

As a reply, @dabeaz suggested I tried doing it with a file:

After seeing how strings can be unpacked, unpacking a file didn't look so weird, but it was still a pleasant surprise!

But it โ€œdoes make senseโ€, after all you can iterate directly over a file, which essentially iterates over the lines of the file.

Grab a CSV file "my_data.csv", for example with this data:

Name, Surnames
John, Doe
Mary, Smith

Then, in your Python REPL, you can get this to work:

>>> header, *data = open("my_data.csv")
>>> header
'Name, Surnames\n'
>>> data
['John, Doe\n', 'Mary, Smith\n']

It is not as useful as using the csv module to read the CSV data in and process it, but it is still a nifty trick.

Come to think of it, if there is a place when this will be useful, probably won't be with CSV files...

I'll let you know if I put this little trick to good use!

That's it for now! Stay tuned and I'll see you around!

Improve your Python ๐Ÿ fluency and algorithm knowledge ๐ŸŽฏ

Get ready for 12 intense days of problem-solving. The โ€œAlgorithm Mastery Bootcampโ€ starts December 1st and it will feature 24 programming challenges, live analysis sessions, a supportive community of like-minded problem-solvers, and more! Join now and become the Python expert others can rely on.

Previous Post Next Post

Blog Comments powered by Disqus.