Use the open() method to access the contents of a file.
FH = open(“filename”, “mode”) –> returns a file object that can be used to manipulate the file’s content.
More efficient way:
with open(“filename”, “mode”) as FH: –> returns a file object
Can loop over the file object:
for line in FH:
r (default) = read from a file
w = write to file (will over-write previous content or create file if it does not exist)
a = append to a file
File object methods:
FH.read() –> puts the entire content of the file in a string
FH.readline() –> returns a single line
FH.readlines() (or list(FH)) –> returns a list/array of all the content of the file
FH.write() –> write content to a file
CSV and JSON
reader() –> returns a reader object. Each row read from the csv file is returned as a list of strings. No automatic data type conversion is performed.
DictReader() –> returns a writer object responsible for converting the data into delimited strings
count = 0
with open(“filename”) as FH:
datareader = csv.reader(FH, delimiter=’,’) # returns an object
for row in datareader: # each row is a list
if count == 0: # header row
count += 1
elif: count > 0 and count < 5: print(row) #each item in the list is a string