Reading Files
You can read a file with the
open
function
open
returns a file object to you
You can read a file object with the
read
method
File Read Example
story.txt
This short story is really short.
reading_files.py
file = open("story.txt")
file.read()
Cursor Movement
seek
method
read
, or use
readline
readlines
Closing a File
with
Blocks
file = open("story.txt")
file.read()
file.close()
file.closed # True
Option 1
with open("story.txt") as file:
file.read()
file.closed # True
Option 2
Writing to Text Files
Writing Files
open
to write to a file
Writing Files Example
with open("haiku.txt", "w") as file:
file.write("Writing files is great\n")
file.write("Here's another line of text\n")
file.write("Closing now, goodbye!")
IMPORTANT: If you open the file again to write, the original contents will be deleted!
Modes for Opening Files
Truncating Files
file.truncate - removes all text starting from the current cursor position
Reading CSV Files
Reading CSV Files
Reading CSV Example
fighters.csv
Name,Country,Height (in cm)
Ryu,Japan,175
Ken,USA,175
Chun-Li,China,165
Guile,USA,182
E. Honda,Japan,185
Dhalsim,India,176
Blanka,Brazil,192
Zangief,Russia,214
reading_csv.py
with open("fighters.csv") as file:
file.read()
Don't do this!
CSV Module
reader
- lets you iterate over rows of the CSV as lists
DictReader
- lets you iterate over rows of the CSV as OrderedDicts
CSV Module Examples
from csv import reader
with open("fighters.csv") as file:
csv_reader = reader(file)
for row in csv_reader:
# each row is a list!
print(row)
from csv import DictReader
with open("fighters.csv") as file:
csv_reader = DictReader(file)
for row in csv_reader:
# each row is an OrderedDict!
print(row)
reader
DictReader
Other Delimiters
from csv import reader
with open("example.csv") as file:
csv_reader = reader(file, delimiter="|")
for row in csv_reader:
# each row is a list!
print(row)
Readers accept a delimiter kwarg in case your data isn't separated by commas.
Writing to CSV Files
Writing CSV Files
writer
- creates a writer object for writing to CSV
writerow
- method on a writer to write a row to the CSV
Using lists
Writing CSV Files Example
Using lists
from csv import writer
with open("fighters.csv", "w") as file:
csv_writer = writer(file)
csv_writer.writerow(["Character", "Move"])
csv_writer.writerow(["Ryu", "Hadouken"])
Writing CSV Files
Using Dictionaries
DictWriter
- creates a writer object for writing using dictionaries
fieldnames
- kwarg for the DictWriter specifying headers
writeheader
- method on a writer to write header row
writerow
- method on a writer to write a row based on a dictionary
Writing CSV Files Example
Using Dictionaries
from csv import DictWriter
with open("example.csv", "w") as file:
headers = ["Character", "Move"]
csv_writer = DictWriter(file, fieldnames=headers)
csv_writer.writeheader()
csv_writer.writerow({
"Character": "Ryu",
"Move": "Hadouken"
})
Dictionaries or Lists?
Recap