Python 07 File
Python 07 File
(text file)
Objectives
After completing this section, you will be able to
• Open a text file for output and write strings or
numbers to the file
• Open a text file for input and read strings or
numbers from the file
2
Agenda
• Reading files
• Writing files
• Exercise
3
Reading files
file object = open(file_name [, access_mode][, buffering])
Paramters detail:
• file_name: The file_name argument is a string value that contains the
name of the file that you want to access.
• access_mode: The access_mode determines the mode in which the
file has to be opened ie. read, write append etc. A complete list of
possible values is given below in the table. This is optional parameter
and the default file access mode is read (r)
• buffering: If the buffering value is set to 0, no buffering will take place.
If the buffering value is 1, line buffering will be performed while
accessing a file. If you specify the buffering value as an integer greater
than 1, then buffering action will be performed with the indicated buffer
size. If negative, the buffer size is the system default(default behavior).
4
A list of the different modes of opening a file
Modes Description
r Opens a file for reading only. The file pointer is placed at the beginning
of the file. This is the default mode.
rb Opens a file for reading only in binary format. The file pointer is placed
at the beginning of the file. This is the default mode.
r+ Opens a file for both reading and writing. The file pointer will be at the
beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The file
pointer will be at the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the
file does not exist, creates a new file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the
file exists. If the file does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if
the file exists. If the file does not exist, creates a new file for reading
and writing.
5
A list of the different modes of opening a file
wb+ Opens a file for both writing and reading in binary format. Overwrites
the existing file if the file exists. If the file does not exist, creates a new
file for reading and writing.
a Opens a file for appending. The file pointer is at the end of the file if the
file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing.
ab Opens a file for appending in binary format. The file pointer is at the end
of the file if the file exists. That is, the file is in the append mode. If the
file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the
end of the file if the file exists. The file opens in the append mode. If the
file does not exist, it creates a new file for reading and writing.
ab+ Opens a file for both appending and reading in binary format. The file
pointer is at the end of the file if the file exists. The file opens in the
append mode. If the file does not exist, it creates a new file for reading
and writing.
6
The file object atrributes:
Once a file is opened and you have one file object, you
can get various information related to that file.
Here is a list of all attributes related to file object:
Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.
file.softspace Returns false if space explicitly required with print, true
otherwise.
7
Reading Files
name = open("filename")
– opens the given file for reading, and returns a file object
8
File Input Template
• A template for reading files in Python:
name = open("filename")
for line in name:
statements
>>> input = open("hours.txt")
>>> for line in input:
... print(line.strip()) # strip() removes \n
9
Exercise
• Write a function input_stats that accepts a file
name as a parameter and that reports the longest
line in the file.
– example input file, carroll.txt:
Beware the Jabberwock, my son,
the jaws that bite, the claws that catch,
Beware the JubJub bird and shun
the frumious bandersnatch.
–>>>
expected output:
input_stats("carroll.txt")
longest line = 42 characters
the jaws that bite, the claws that catch,
10
Exercise Solution
def input_stats(filename):
input = open(filename)
longest = ""
for line in input:
if len(line) > len(longest):
longest = line
11
Exercise
• Suppose we have this hours.txt data:
123 Suzy 9.5 8.1 7.6 3.1 3.2
456 Brad 7.0 9.6 6.5 4.9 8.8
789 Jenn 8.0 8.0 8.0 8.0 7.5
12
Exercise Answer
hours.py
1 input = open("hours.txt")
2 for line in input:
3 id, name, mon, tue, wed, thu, fri = line.split()
4
5 # cumulative sum of this employee's hours
6 hours = float(mon) + float(tue) + float(wed) + \
7 float(thu) + float(fri)
8
9 print(name, "ID", id, "worked", \
10 hours, "hours: ", hours/5, "/ day"
13
Writing Files
name = open("filename", "w")
name = open("filename", "a")
– opens file for write (deletes previous contents), or
– opens file for append (new data goes after previous
data)
14
Exercise
• Write code to read a file of gas prices in USA and
Belgium:
8.20 3.81 3/21/11
8.08 3.84 3/28/11
8.38 3.92 4/4/11
...
15
Directories in Python:
All files are contained within various directories, and Python has no problem
handling these too. The os module has several methods that help you
create, remove, and change directories.
16
Directories in Python:
os.path module
17
os library
The mkdir() Method:
You can use the mkdir() method of the os module to create directories in
the current directory. You need to supply an argument to this method,
which contains the name of the directory to be created.
Syntax:
os.mkdir("newdir")
Example:
import os # Create a directory "test"
os.mkdir("test")
18
os library
The chdir() Method:
You can use the chdir() method to change the current
directory. The chdir() method takes an argument, which
is the name of the directory that you want to make the
current directory.
Syntax:
os.chdir("newdir")
Example:
import os
os.chdir("/home/newdir")
19
os library
The getcwd() Method:
The getcwd() method displays the current working directory.
Syntax:
os.getcwd()
Example:
import os
os.getcwd()
20
os library
The rmdir() Method:
The rmdir() method deletes the directory, which is passed as an
argument in the method.
Before removing a directory, all the contents in it should be
removed.
Syntax:
os.rmdir('dirname')
Example:
import os
os.rmdir( "/tmp/test" )
21
File & Directory Related Methods
File & Directory Related Methods:
There are three important sources which provide a wide range of utility methods
to handle and manipulate files & directories on Windows and Unix operating
systems. They are as follows:
– File Object Methods: The file object provides functions to manipulate files.
– OS Object Methods.: This provides methods to process files as well as
directories.
22