Contents
- file_read.py
- file_search.py
- for_file_read.py
- using_readline.py
file_read.py 1/4
[top][prev][next]
# Opens a file, reads it, and prints out its contents.
# by Sara Sprenkle
FILENAME="data/famous_pairs.txt"
# creates a new file object, opening the file in read mode
myFile = open(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()
# display the contents of the file
print(contents)
file_search.py 2/4
[top][prev][next]
# Given a file and a term to search for,
# find which lines the term is on and the
# total number of lines that contained that term
# By CSCI 111
FILENAME="data/years.dat"
print("This program will find out how many lines the given search term")
print("is on in", FILENAME,"and show those lines")
print()
print("Looking at file", FILENAME)
# open the file for reading
fileobj = open(FILENAME, "r")
# get user input for this later:
searchFor = "Junior"
numSearchFor = 0
numLines = 0
# read through each line of file
for line in fileobj:
line = line.rstrip()
numLines += 1
# does the line contain what we're searching for?
if searchFor in line:
# update the accumulator
numSearchFor += 1
print( numLines, line )
fileobj.close()
print()
print("I found", numSearchFor, searchFor, "in file.")
for_file_read.py 3/4
[top][prev][next]
# Opens a file, reads the file one line at a time, and prints the
# contents
# by Sara Sprenkle
FILENAME="data/famous_pairs.txt"
# creates a new file object, opening the file in "read" mode
dataFile = open(FILENAME, "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()
using_readline.py 4/4
[top][prev][next]
# One way to use readline()
# by Sara Sprenkle
FILENAME="data/famous_pairs.txt"
# creates a new file object, opening the file in "read" mode
dataFile = open(FILENAME, "r")
# reads in the file line-by-line and prints the content of the file
line = dataFile.readline()
while line != "":
print(line) # just to do something with that line.
line = dataFile.readline()
# What happens when we try to read the next line, after we have already
# read through the file?
#line = dataFile.readline()
# Answer: That line is also an empty string:
#print(line)
# close the file with the method "close"
dataFile.close()
Generated by GNU Enscript 1.6.6.