0% found this document useful (0 votes)
8 views17 pages

Lecture 29

The document discusses working with files in Python including reading from and writing to files, opening and closing files, and reading/writing numeric and text data to files. Common file operations like checking if a file exists, opening files in different modes, reading/writing data, and appending data are covered.

Uploaded by

Maxi Brad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views17 pages

Lecture 29

The document discusses working with files in Python including reading from and writing to files, opening and closing files, and reading/writing numeric and text data to files. Common file operations like checking if a file exists, opening files in different modes, reading/writing data, and appending data are covered.

Uploaded by

Maxi Brad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Computer Science 1001

Lecture 29

Lecture Outline

• File input/output

– CS1001 Lecture 29 –
Files

• Files can be used to store data.

• Data used/computed in a program is temporary.


Unless data is saved into a file, it will be lost when
the program terminates.

• Programs can also read data from a file.

• A file is placed in a directory in the file system. The


location of the file is given as either an absolute
filename or a relative filename.

– CS1001 Lecture 29 – 1
Files

• We will learn to work with text files.

• Text files are encoded in a scheme such as ASCII or


Unicode.

• When a file is opened for writing or reading, a


marker called a file pointer is positioned at the
beginning of the file.

• When data is read from or written to the file, the


file pointer moves forward.

• At any time, the file pointer indicates the last


position read or written.

– CS1001 Lecture 29 – 2
Working with files

• The basic file operations are:


1. If we are planning to read from or add to a file,
we should check that the file exists.
2. If the file exists or if a new file will be created,
open the file, indicating how the file will be used.
3. Perform the read and/or write operations on the
file.
4. Close the file.

– CS1001 Lecture 29 – 3
Testing a file’s existence

• To check whether a file exists, we can use the


os.path module, which provides many functions
related to pathnames.

• We first import the module os.path.

• The function isfile(fileName) returns True if


fileName is an existing file.

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

• To read from or write to a file, we first have to open


the file.

• In Python, opening the file creates a file object,


which is done by calling the open function:

file = open(filename, mode)

• The mode indicates how the file will be used.


Possible values include:
Mode Description
"r" Open a file for reading (default).
"w" Open a file for writing. If the file already exists it
will be overwritten.
"a" Open a file for writing, appending to the end of
the file if the file already exists.

– CS1001 Lecture 29 – 5
Reading data

• There are three methods to read data from a file:


– read(size)
to read at most size bytes of data from the file
and return it as a string. If size is omitted the
entire file is read. If the end of the file has been
reached, an empty string ("") is returned.
– readline()
to read a single line from a file as a string (with
a newline character, \n, at the end). An empty
string is returned "" when the end of the file has
been reached. If a blank line is read, the returned
string will be "\n".
– readlines()
to read all lines in the file into a list of strings.
Each element in the list corresponds to a line in
the file.

– CS1001 Lecture 29 – 6
Example: reading data

import os.path

filename = input("Enter the filename: ")


if os.path.isfile(filename):
fileIn = open(filename,"r")

# read one line


line = fileIn.readline()
print(line)

# read 5 characters
chars = fileIn.read(5)
print(chars) # no newline char in chars

# read all remaining lines


all_lines = fileIn.readlines()
print("The file has",len(all_lines),"lines remaining")
print(all_lines)
print()

fileIn.seek(0) # go to beginning of file


print("The entire file:")
entire_file = fileIn.read()
print(entire_file)
fileIn.close()

– CS1001 Lecture 29 – 7
Example: reading data

Executing the above code on the file:


This is the first line.
This is the second line.
This is the third line.
This is the fourth line.
This is the last line.

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’]

The entire file:


This is the first line.
This is the second line.
This is the third line.
This is the fourth line.
This is the last line.

– CS1001 Lecture 29 – 8
Example: reading data

• We can also use a for loop to iterate over lines in


the file, as in:

import os.path

filename = input("Enter the filename: ")


if os.path.isfile(filename):
fileIn = open(filename,"r")
# use a for loop to read all lines in a file
for line in fileIn:
print(line)
fileIn.close()

• Sample output:

This is the first line.

This is the second line.

This is the third line.

This is the fourth line.

This is the last line.

– CS1001 Lecture 29 – 9
Writing data

• To write data to a file we can use the write()


function, passing it the string that we want to
output.

• The write() function returns the number of


characters written.

• The write function does not automatically insert


the newline character ("\n"), it should be included
in the string passed to write.

• For example,

outfile = open("test.txt", "w")


outfile.write("Welcome to Python\n")
outfile.write("Hello world!\n")
outfile.close()

creates a file with contents:

Welcome to Python
Hello world!

– CS1001 Lecture 29 – 10
Appending data

• We can append data to the end of an existing file


by using the mode "a" when opening the file.

• For example,

import os.path

filename = input("Enter the filename: ")


if os.path.isfile(filename):
fileOut = open(filename,"a")
# the file pointer is positioned at the end of the file
# add new lines to the file
fileOut.write("A new line\n")
fileOut.close()

• Using the file created on the previous slide, we would


have:

Welcome to Python
Hello world!
A new line

– CS1001 Lecture 29 – 11
Reading and writing numeric data

• To write numbers to a file, you must first convert


them into strings and use the write method to write
them to the file.

• To read numbers correctly they must be separated


by whitespace characters such as " ", "\t", "\n".

– CS1001 Lecture 29 – 12
Example: writing/reading numeric data

Here, we write 10 random integers between 0 and 9


(inclusive) to a file called numbers.txt. We then read
the values from the file and output them to the screen.
from random import randint

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

# Open file for reading data


infile = open("Numbers.txt", "r")
s = infile.read()
infile.close() # Close the file
numbers = [eval(x) for x in s.split()]
for number in numbers:
print(number, end = " ")

main() # Call the main function

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

You might also like