Topics This week: File input and output Python Programming, 2/e 1

Preview:

Citation preview

1

TopicsThis week:

File input and output

Python Programming, 2/e

Input/OutputThus far we have only been able to get input

from the user and produce output to the screenLimits the scope of our programsWhat if we wanted to search in a book? We would have to type the book into our program

each time!

Our output was limited by what we could display to the screenAfter our program completed the output was gone!

Files: Multi-line StringsA file is a sequence of data that is stored in

secondary, persistent memory (such as a disk drive).

Files can contain any data type, but the easiest to work with would be text.

A text file usually contains more than one line of text.

Python uses the standard newline character (\n) to mark line breaks.

Multi-Line StringsHello

World

Goodbye 32

When stored in a file:Hello\nWorld\n\nGoodbye 32\n

Multi-Line StringsThis is exactly the same thing as embedding \n

in print statements.

Remember, these special characters only affect things when printed. They don’t do anything during evaluation.

File ProcessingThe process of opening a file involves

associating a file on disk with an object in program memory.

We can manipulate the file by manipulating this object.Read from the fileWrite to the file

File ProcessingWhen done with the file, it needs to be closed.

Closing the file causes any outstanding operations and other bookkeeping for the file to be completed.

In some cases, not properly closing a file could result in data loss.

File Processing ExampleReading a file into a word processor

File opened for inputContents read into RAMFile closedChanges to the file are made to the copy stored in

memory, not on the disk.

Save:Backup copy of file madeFile opened for outputRAM version written to fileFile closed

File ProcessingWorking with text files in Python

Associate a file with a file object using the open function<filevar> = open(<name>, <mode>)

Name is a string with the actual file name on the disk. The mode is either ‘r’ or ‘w’ depending on whether we are reading or writing the file.There are also other modes

Infile = open("numbers.dat", "r")

File Methods<file>.read() – returns the entire remaining

contents of the file as a single (possibly large, multi-line) string

<file>.readline() – returns the next line of the file. This is all text – up to and including the next newline character at the end of the line

<file>.readlines() – returns a list of the remaining lines in the file. Each list item is a single line including the newline characters.

File Processing

Prompt the user for a file name

Open the file for reading

The file is read as one single string and stored in the variable named data

# Prints a file to the screen.def main(): fname = input("Enter filename: ") infile = open(fname,'r') data = infile.read() print(data) infile.close()main()

File Processingreadline can be used to read the next line from a

file, including the trailing newline character

infile = open(someFile, "r")for i in range(5):

line = infile.readline()print (line[:-1])

infile.close()

This reads the first 5 lines of a file, then closes it

Slicing is used to strip out the newline characters at the ends of the lines

File ProcessingAnother way to loop through the contents of a

file is to read it in with readlines and then loop through the resulting list.

infile = open(someFile, "r")for line in infile.readlines():

# Line processing hereinfile.close()

File ProcessingPython treats the file object itself as a sequence

of lines!

infile = open(someFile, "r")for line in infile:

# process the line hereinfile.close()

File ProcessingOpening a file for writing prepares the file to

receive data

If you open an existing file for writing, you wipe out the file’s contents. If the named file does not exist, a new one is created.

Outfile = open("mydata.out", "w")

Actual writing:print(<expressions>, file=Outfile)Outfile.write(<string>)Print takes multiple arguments; write only one, a

string

Example Program: Batch Usernames

Batch mode processing is where program input and output are done through files (the program is not designed to be interactive)

Let’s create usernames for a computer system where the first and last names come from an input file.

Helpful String MethodOne of these methods is split. This will split a

string into substrings based on spaces.

>>> "Hello string methods!".split()

['Hello', 'string', 'methods!']

Another String MethodSplit can be used on characters other than

space, by supplying the character as a parameter.

>>> "32,24,25,57".split(",")

['32', '24', '25', '57']

>>>

19

CQ: How many?What does the following program print?

S = "a,b,,d,e"print(len(S.split(",")))

A. 8

B. 5

C. 4

Python Programming, 2/e

Example Program: Batch Usernames

# userfile.py# Program to create a file of usernames in batch mode.

def main(): print ("This program creates a file of usernames from a") print ("file of names.")

# get the file names infileName = input("What file are the names in? ") outfileName = input("What file should the usernames go in? ")

# open the files infile = open(infileName, 'r') outfile = open(outfileName, 'w')

Example Program: Batch Usernames

# process each line of the input file for line in infile: # get the first and last names from line first, last = line.split() # create a username uname = (first[0]+last[:7]).lower() # write it to the output file outfile.write(uname+”\n”)

# close both files infile.close() outfile.close() print("Usernames have been written to", outfileName)

Example Program: Batch Usernames

Things to note:It’s not unusual for programs to have multiple

files open for reading and writing at the same time.

The <string>.lower() method is used to convert the names into all lower case, in the event the names are mixed upper and lower case.

We manually added a newline “\n” after each name, this ensures each id is on a separate lineWhat happens if we do not do this?

When we split the string we were “parsing”

Methods on Filesobject.method() syntax: this time files are our

objectExample: file = open(“myfile”, “w”)

file.read() -- reads the file as one string

file.readlines() – reads the file as a list of strings

file.readline() – reads one line from the file

file.write() – allows you to write a string to a file

file.close() – closes a file

Example: Writing to a Filedef formLetter(gender ,lastName,city): file = open("formLetter.txt",”w") file.write("Dear ") if gender =="F": file.write("Ms. "+lastName+":\n") if gender =="M": file.write("Mr. "+lastName+":\n") file.write("I am writing to remind you of the offer ") file.write("that we sent to you last week. Everyone in ") file.write(city+" knows what an exceptional offer this is!") file.write("Sincerely ,\n") file.write("I.M. Acrook, Attorney at Law") file.close()

Example: result>>> formLetter("M","Guzdial","Decatur”)

Dear Mr. Guzdial:

I am writing to remind you of the offer that we sent to you last week. Everyone in Decatur knows what an exceptional offer this is!

Sincerely,

I.M. Acrook, Attorney at Law

File Output is ImportantAllows your programs to produce results that are

viewable by other programs

Allows you to retain computed results after a program terminates

Python’s Standard LibraryPython has an extensive

library of modules that come with it.

The Python standard library includes modules that allow us to access the Internet, deal with time, generate random numbers, and…access files in a directory.

Accessing pieces of a module

We access the additional capabilities of a module using dot notation, after we import the module.

How do you know what code is there?Check the online documentation.There are books like Python Standard Library that

describe the modules and provide examples.

The OS ModuleThe OS module provides an interface to the

underlying operating systemAllows your program to request resources/actions to

be performed on your program’s behalf

os.chdir(path) – changes the current working directory

os.listdir(path) – returns a list of all entries in the directory specified by path

os.curdir – returns what directory the program is executing in (i.e. the current directory)

The OS Path submoduleOnce you import os – import os – you can also

use the path module

os.path.isfile(path) – returns true if the path specified is a file, returns false otherwiseUse this method to perform a check to see if the

user provided input for a valid file

Example: error checking

import osdef chkPath(): path = input("type a file name: ") if os.path.isfile(path): return True,path else: return False,pathdef main(): chk = True while chk: chk,file = chkPath() if chk: print('file', file, 'exists') else: print('file', file,'does not exist')

main()

Recommended