Lecture 29
Lecture 29
Lecture 29
Lecture Outline
• File input/output
– CS1001 Lecture 29 –
Files
– CS1001 Lecture 29 – 1
Files
– CS1001 Lecture 29 – 2
Working with files
– CS1001 Lecture 29 – 3
Testing a file’s existence
import os.path
if os.path.isfile("info.dat"):
# True if the file info.dat exists in the current directory
print("info.dat exists")
– CS1001 Lecture 29 – 4
Opening a file
– CS1001 Lecture 29 – 5
Reading data
– CS1001 Lecture 29 – 6
Example: reading data
import os.path
# read 5 characters
chars = fileIn.read(5)
print(chars) # no newline char in chars
– CS1001 Lecture 29 – 7
Example: reading data
produces:
This is the first line.
This
The file has 4 lines remaining
[’is the second line.\n’, ’This is the third line.\n’, ’This is the
fourth line.\n’, ’This is the last line.\n’]
– CS1001 Lecture 29 – 8
Example: reading data
import os.path
• Sample output:
– CS1001 Lecture 29 – 9
Writing data
• For example,
Welcome to Python
Hello world!
– CS1001 Lecture 29 – 10
Appending data
• For example,
import os.path
Welcome to Python
Hello world!
A new line
– CS1001 Lecture 29 – 11
Reading and writing numeric data
– CS1001 Lecture 29 – 12
Example: writing/reading numeric data
def main():
# Open file for writing data
outfile = open("Numbers.txt", "w")
for i in range(10):
outfile.write(str(randint(0, 9)) + " ")
outfile.close() # Close the file
Sample output:
4 3 4 6 2 6 0 5 9 1
– CS1001 Lecture 29 – 13
Example: binary search
def binarySearch(key, lst):
low, high = 0, len(lst)-1 # starting indices
while low <= high:
mid = (low + high)//2 # get middle index
if key == lst[mid]:# found the key
return mid
elif key < lst[mid]: # move high to search first half
high = mid -1
elif key > lst[mid]: # move low to search second half
low = mid + 1
return -1 # didn’t find the key
def main():
infile = open("numbers.dat","r")
lst = []
for line in infile: # read numbers, one per line and add to list
lst.append(eval(line))
print("Original list:")
print(lst)
lst.sort() # list must be sorted
print("Sorted list:")
print(lst)
k = int(input("Value to search for: "))
location = binarySearch(k,lst)
if location != -1:
print("Value is at position: ", location)
else:
print("Value not found")
main()
– CS1001 Lecture 29 – 14
Example: binary search
Sample output:
Original list:
[3, 4, 7, 1, 5, 2, 4, 8, 9, 3]
Sorted list:
[1, 2, 3, 3, 4, 4, 5, 7, 8, 9]
Value to search for: 4
Value is at position: 4
Original list:
[3, 4, 7, 1, 5, 2, 4, 8, 9, 3]
Sorted list:
[1, 2, 3, 3, 4, 4, 5, 7, 8, 9]
Value to search for: 1
Value is at position: 0
Original list:
[3, 4, 7, 1, 5, 2, 4, 8, 9, 3]
Sorted list:
[1, 2, 3, 3, 4, 4, 5, 7, 8, 9]
Value to search for: 6
Value not found
– CS1001 Lecture 29 – 15
Example: selection sort
• We can use our selection sort function to sort data
read from a file into a list as follows:
def main():
lst=[]
filename = input("Enter filename: ")
infile = open(filename,"r")
line = infile.readline()
while line != "": # read to end of file
lst.append(eval(line))
line = infile.readline()
print("Original list:")
print(lst)
selectionSort(lst)
print("Sorted list:")
print(lst)
if __name__=="__main__":
main()
• Sample output:
Enter filename: to_sort.dat
Original list:
[2.5, 3.46, 5.1, 85.2, 6.49, 5.9, 8.51, 3.264, 0.5, 2.9, 5.7,
6.498, 42.1]
Sorted list:
[0.5, 2.5, 2.9, 3.264, 3.46, 5.1, 5.7, 5.9, 6.49, 6.498, 8.51,
42.1, 85.2]
– CS1001 Lecture 29 – 16