Contents
- file_read2.py
- file_read3.py
- file_read.py
- file_search.py
file_read2.py 1/4
[top][prev][next]
# Opens a file, reads the file one line at a time, and prints the
# contents,
# by Sara Sprenkle
FILENAME="data/years.dat"
# opens the file in "read" mode
dataFile = file(FILENAME, "r")
# reads in the file, line-by-line and prints the content of the file
line = dataFile.readline()
while line != "":
print line,
line = dataFile.readline()
# close the file with the method "close"
dataFile.close()
file_read3.py 2/4
[top][prev][next]
# Opens a file, reads the file one line at a time, and prints the
# contents,
# by Sara Sprenkle
FILENAME="data/years.dat"
# opens the file in "read" mode
dataFile = file(FILENAME, "r")
#dataFile = file("data/years.dat", "r")
# reads in the file line-by-line and prints the content of the file
for line in dataFile:
line = line.strip()
print line
# close the file with the method "close"
dataFile.close()
file_read.py 3/4
[top][prev][next]
# Opens a file, reads it, and prints out its contents.
# by Sara Sprenkle
FILENAME="data/years.dat"
myFile = file(FILENAME, "r")
# read the file and put it into one string
contents = myFile.read()
# close the file when you're done reading the file
myFile.close()
# print out the contents of the file
print contents,
file_search.py 4/4
[top][prev][next]
# Opens a file, reads the file one line at a time,
# searching for data from the user
# by CS111
FILENAME="data/years.dat"
searchTerm = raw_input("What are you looking for? ")
# opens the file in "read" mode
dataFile = file(FILENAME, "r")
# Set up accumulators
lineNum=0
numOccurrences=0
# reads in the file and prints the content of the file
for line in dataFile:
lineNum+=1
# strip is a string method that
# removes the trailing and beginning whitespace
line = line.strip()
# look for the line
if searchTerm in line:
print "Found %s in line %d: \"%s\"" % (searchTerm, lineNum, line)
numOccurrences+=1
# close the file with the method "close"
dataFile.close()
# Report findings ...
print searchTerm, "was found", numOccurrences, "times"
Generated by GNU enscript 1.6.4.