Previous Lecture Lecture 19 Next Lecture

Lecture 19, Tue 03/12

File IO cont.

Recorded Lecture: 3_12_24

Common Ways to Read Data From Files (cont.)

This is Line 1
This is Line 2
This is Line 3
# Reading entire contents of file into program
infile = open('example.txt') 
data = infile.read()
print(data)
infile.close()
# Reading a single line (up to and including \n) in file
infile = open('example.txt')
data = infile.readline()
print(data)
data = infile.readline()
print(data)
data = infile.readline()
print(data)
infile.close()
# Creating a list where elements are a line (includes \n)
infile = open('example.txt')
data = infile.readlines()
print(data)
infile.close()
# Traversing through the file line-by-line in a for loop (includes \n)
infile = open('example.txt')
for line in infile:
	print(line)
infile.close()

Writing to Files

# Example writing to a new file `example2.txt`
outfile = open('example2.txt', 'w')
outfile.write("This is something new!")
outfile.close()
# Example of overwriting contents of a file
outfile = open('example2.txt', 'w')
outfile.write("Completely new text ... old text is gone!\n")
outfile.write("This is a new new line")
outfile.close()

Appending to Files

# Example of appending contents of a file
outfile = open('example2.txt', 'a')
outfile.write("Something new!\n")
outfile.write("Another line!")
outfile.close()
# Example copying / writing from a file to another file.
infile = open('example.txt', 'r')
outfile = open('copy.txt', 'w')
for line in infile:
	outfile.write(line)
infile.close()
outfile.close()

with Statement

with open('example.txt', 'w') as outfile:
	outfile.write("Writing to the file - line 1\n")
	outfile.write("Exiting with block")

# After with block is finished executing, outfile is automatically closed
print("Done")

The os Module

print(os.path.join("Users", "richert", "Desktop", "UCSB", "CS8W", "lecture.py")) # Users/richert/Desktop/UCSB/CS8W/lecture.py
# Note that the file separator would be different if I ran this on Windows

The CSV Reader

Student 1,100,98,100
Student 2,100,100,95
Student 3,100,95,90
import csv

with open('sample.csv', 'r') as csvFile:
	csvReader = csv.reader(csvFile) # could use a different delimiter param
	for row in csvReader:
		print(row)
import csv

with open('sample.csv', 'r') as csvFile:
	csvReader = csv.reader(csvFile)

	for row in csvReader:
		total = 0
		for i in range(1, len(row)):
			total += float(row[i])
		print(f"{row[0]}: average = {total / 3:.2f}")
import csv

def dropLowest(fileName):
	with open(fileName, 'r') as csvFile:

		with open("updatedSample.csv", 'w') as outFile:
			csvReader = csv.reader(csvFile)
			for row in csvReader:
				maxValue = 1000
				minIndex = -1
				for i in range(1, len(row)):
					if float(row[i]) < maxValue:
						maxValue = float(row[i])
						minIndex = i
				row.pop(minIndex)

				newRow = ""
				for element in row:
					newRow += element + ","
				newRow = newRow[:-1]
				outFile.write(newRow + "\n")

dropLowest("sample.csv")