Working with Files

Importing files _without_ Pandas

There are a lot of different types of files. This is the way to interact with a lot of those files, focusing on local files (not API calls)

A Quick Aside for Modules

  • Libraries or Packages are properly called Modules

  • Other .py files are also Modules, and are imported the same way (no .py extension needed)

  • Actual docs get opened a little differently

Opening Basic Files

This one is pretty straight forwards.

# Reading a file; do this unless you're editing it
with open('real_cool_document.txt') as cool_doc:
  cool_contents = cool_doc.read()
  print(cool_contents)

# Or for just the top line, to preserve performance
with open('just_the_first.txt') as first_line_doc:
  first_line = first_line_doc.readline()
  print(first_line)

# Writing to a file
with open('bad_bands.txt', 'w') as bad_bands_doc:
  bad_bands_doc.write('Nickelback')

# Opening and appending to a file
with open('cool_dogs.txt', 'a') as cool_dogs_file:
  cool_dogs_file.write("Air Buddy")

CSV Fiddling

Unerringly, pandas tends to do this better, but for the sake of completeness, here's how to do it with csv. It's a lower-level library and allows for iteration in case the data is truly terrible.

Writing to a .csv...

Freaking JSON

I hate JSON because it's not a relational database. It's annoying, and perpeptually object-oriented despite mainly being implemented in bloody functional programming sets. Here's how you deal with it anyway, sorry you're here again future Katt.

Opening JSON

Adding to JSON

Last updated