0% found this document useful (0 votes)
4 views

Week 13 Files

Uploaded by

a.ahgv1453
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)
4 views

Week 13 Files

Uploaded by

a.ahgv1453
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/ 24

File Input/Output

Why Use Files?


• Until now, the Python programs you've been
writing are simple for input/output
– User types input at the keyboard
– Results (output) are displayed in the console
• This is fine for short and simple input…
– But what if we want to average 50 numbers,
and mess up when entering the 37th one?

2
What is File I/O?
• One solution is to read the information from a
file on your computer
– You could even write information to a file

• This process is called File I/O


– "I/O" stands for "input/output“
– Python has built-in functions that make this easy

3 https://www.codecademy.com/courses/python-intermediate-en-OGNHh/0/1
File I/O Example Usage
• “Read” in a file using a word processor
– File opened
– Contents read into memory (RAM)
– File closed
– IMPORTANT: Changes to the file are
made to the copy stored in memory,
not the original file on the disk

4
File I/O Example Usage
• “Write” a file using a word processor
– (Saving a word processing file)
– Original file on the disk is reopened in a
mode that will allow writing
• This actually erases the old contents!
– Copy the version of the document stored in
memory to the original file on disk
– File is closed

5
File Processing
• In order to do some operations with files, we
need to be able to perform certain operations:
– Associate an external file with a program object
• Opening the file
– Manipulate the file object
• Reading from or writing to the file object
– Close the file
• Making sure the object and file match
6
Syntax: Opening a File
Syntax for open() Function
myFile = open(FILE_NAME [, ACCESS_MODE][, BUFFERING])

FILE_NAME

• This argument is a string the contains the


name of the file you want to access
– "input.txt"
– "numbers.dat"
– "roster.txt"

8
Syntax for open() Function
myFile = open(FILE_NAME [, ACCESS_MODE][, BUFFERING])

ACCESS_MODE (optional argument)

• This argument is a string that determines


which of the modes the file is to be opened in
– "r" (open for reading)
– "w" (open for writing)
– "a" (open for appending)

9
Syntax for open() Function
myFile = open(FILE_NAME [, ACCESS_MODE][, BUFFERING])

BUFFERING (optional argument)

• This argument is an integer that specifies to


desired buffer size for the file we won’t be using
– 0 (unbuffered) buffering much (if
– 1 (line buffered) at all) in this class

– >1 (buffer of approximately that size in bytes)

10
Examples of Using open()
• In general, we will use commands like:
testFile = open("scores.txt")
dataIn = open("old_stats.dat")
dataOut = open("stats.dat", "w")
• We will ignore the optional buffering argument
scores.txt
an example 2.5 8.1 7.6 3.2 3.2
input file 3.0 11.6 6.5 2.7 12.4
8.0 8.0 8.0 8.0 7.5
11
File Processing: Reading
Using File Objects to Read Files
myFile = open("myStuff.txt")

• This line of code does three things:


1. Opens the file “myStuff.txt”
2. In the “reading” mode (which is the default)
3. Assigns the opened file to the variable myFile
• myFile is a variable of type file object
• Once the file is open, we can start reading it
13
Three Ways to Read a File
• There are three different ways to read in a file:

1. Read the whole file in as one big long string


myFile.read()
2. Read the file in one line at a time
myFile.readline()
3. Read the file in as a list of strings (each is one line)
myFile.readlines()

14
Entire Contents into One String
>>> info = open("hours.txt")
>>> wholeThing = info.read()
>>> wholeThing
'123 Susan 12.5 8.1 7.6 3.2\n456 Brad 4.0
11.6 6.5 2.7 12\n789 Jenn 8.0 8.0 8.0 8.0
7.5\n'

our input file


hours.txt
123 Susan 12.5 8.1 7.6 3.2
456 Brad 4.0 11.6 6.5 2.7 12
789 Jenn 8.0 8.0 8.0 8.0 7.5
15 https://courses.cs.washington.edu/courses/cse142/11au/python/06-files.ppt
Entire Contents into One String
>>> info = open("hours.txt")
>>> wholeThing = info.read()
>>> wholeThing
'123 Susan 12.5 8.1 7.6 3.2\n456 Brad 4.0
11.6 6.5 2.7 12\n789 Jenn 8.0 8.0 8.0 8.0
7.5\n'

notice that escape sequence our input file


(\n) is being printed, instead of hours.txt
the text starting on a new line 123 Susan 12.5 8.1 7.6 3.2
456 Brad 4.0 11.6 6.5 2.7 12
789 Jenn 8.0 8.0 8.0 8.0 7.5
16 https://courses.cs.washington.edu/courses/cse142/11au/python/06-files.ppt
One Line at a Time
>>> info = open("hours.txt")
>>> lineOne = info.readline()
>>> lineOne
'123 Susan 12.5 8.1 7.6 3.2\n'
>>> lineTwo = info.readline()
'456 Brad 4.0 11.6 6.5 2.7 12\n'
our input file
hours.txt
123 Susan 12.5 8.1 7.6 3.2
456 Brad 4.0 11.6 6.5 2.7 12
789 Jenn 8.0 8.0 8.0 8.0 7.5
17 https://courses.cs.washington.edu/courses/cse142/11au/python/06-files.ppt
As a List of Strings
>>> info = open("hours.txt")
>>> listOfLines = info.readlines()
>>> listOfLines
['123 Susan 12.5 8.1 7.6 3.2\n',
'456 Brad 4.0 11.6 6.5 2.7 12\n',
'789 Jenn 8.0 8.0 8.0 8.0 7.5\n']
our input file
hours.txt
123 Susan 12.5 8.1 7.6 3.2
456 Brad 4.0 11.6 6.5 2.7 12
789 Jenn 8.0 8.0 8.0 8.0 7.5
18 https://courses.cs.washington.edu/courses/cse142/11au/python/06-files.ppt
Using for Loops to Read in Files
• Instead of reading them manually, use a
for loop to iterate through the file line by line
>>> info = open("hours.txt")
>>> for eachLine in info:
... print(eachLine)
...
123 Susan 12.5 8.1 7.6 3.2

456 Brad 4.0 11.6 6.5 2.7 12

789 Jenn 8.0 8.0 8.0 8.0 7.5

19
A Better Way to Read One Line at a Time
• Instead of reading them manually, use a
for loop to iterate through the file line by line
>>> info = open("hours.txt")
>>> for eachLine in info: why are there all
... print(eachLine)
these empty lines???
...
123 Susan 12.5 8.1 7.6 3.2 now that we’re
calling print(),
456 Brad 4.0 11.6 6.5 2.7 12
the \n is printing
789 Jenn 8.0 8.0 8.0 8.0 7.5 out as a new line

20
Whitespace
Whitespace
• Whitespace is any “blank” character, that
represents space between other characters
• For example: tabs, newlines, and spaces
"\t" "\n" " "

• When we read in a file, we can get whitespace


– Sometimes, we don’t want to keep it

22
Removing the Newline from the End
• To remove the escaped newline sequence (\n)
from a string we read in, we can use slicing

myString = myString[:-1]

0 1 2 3

d o g \n
-4 -3 -2 -1
myString
23
Removing the Newline from the End
• To remove the escaped newline sequence (\n)
from a string we read in, we can use slicing

myString = myString[:-1]

don’t remove 0 1 2 3
anything from the
beginning d o g \n
just remove the very -4 -3 -2 -1
last character myString
24

You might also like