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

PHY 3032 Chapter 10A - File Handling in Python 3

This document provides an overview of file handling in Python 3, covering essential functions for creating, reading, updating, and deleting files. It outlines the learning objectives, explains how to open and close files, and details various file access modes and methods for reading and writing data. Additionally, it includes practical examples for reading entire files, specific parts, and writing to files, emphasizing best practices such as closing files after use.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

PHY 3032 Chapter 10A - File Handling in Python 3

This document provides an overview of file handling in Python 3, covering essential functions for creating, reading, updating, and deleting files. It outlines the learning objectives, explains how to open and close files, and details various file access modes and methods for reading and writing data. Additionally, it includes practical examples for reading entire files, specific parts, and writing to files, emphasizing best practices such as closing files after use.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

13/06/2020 PHY 3032 Chapter 10A - File Handling in Python 3

File Handling
File handling is an important part of computer programming. Python programs, often have to read information
that was saved in files. Python has several functions for creating , reading , updating , and
deleting files.

Learning Objectives
By the end of this lesson, you will learn how to

open and close files;


read an entire file file;
read only parts of a file;
read a single line from a file;
read multiple lines from a file;
Write lines to an existing file;
create a new text file;
create a new CSV file;
create a new CSV file from a list;
get the position of a file pointer in a file
change the position of a file pointer in a file.

Opening and closing Files


Python provides basic functions and methods necessary to manipulate files by default. You can do most of
the file manipulation using a file object.

The open() function


Before you can read or write or update a file, you have to open it using Python's builtin open()
function. The open() function takes two parameters; filename , and mode and creates a file
object .

The general recipe for opening a file with open() is given below:

f ile object = open(f ilename [, mode])

The filename argument is a string value that contains the name of the file that you want to access.
The mode determines the mode in which the file has to be opened. This is optional parameter and the
default file access mode is read i.e. r .

The file object which would be utilized to call other support methods associated with it.

localhost:8888/nbconvert/html/PHY 3032 Chapter 10A - File Handling in Python 3 .ipynb?download=false 1/19


13/06/2020 PHY 3032 Chapter 10A - File Handling in Python 3

File access modes and descriptions


There are different access modes (methods) for opening a file:

r : Opens a file for reading only . If the file does not exit, you get an error. The file pointer is placed
at the beginning of the file.
rb : Opens a file for reading only in binary format . The file pointer is placed at the
beginning of the file.
r+ : Opens a file for both reading and writing . The file pointer placed at the beginning of the
file.
rb+ : Opens a file for both reading and writing in binary format . The file pointer placed
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.
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. 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. 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. 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. If the file does not exist, it creates a new file for reading and writing.

To open a file for reading, it is enough to specify the name of the file.

Open the text file "black_sheet.txt" for reading only.

In [1]:

file = open("black_sheep.txt")

You can also open a file for reading by specify the name of the file and file access mode:

Open the text file "black_sheet.txt" for reading only.

In [2]:

file = open("black_sheep.txt","r")

localhost:8888/nbconvert/html/PHY 3032 Chapter 10A - File Handling in Python 3 .ipynb?download=false 2/19


13/06/2020 PHY 3032 Chapter 10A - File Handling in Python 3

The file object attributes and descriptions


Once a file is opened and you have one file object, you can get various information related to that file
through attributes related to file object.

file.name : Returns name of the file.


file.mode : Returns access mode with which file was opened.
file.closed : Returns true if file is closed, false otherwise.

In [3]:

print("Name of file : ",file.name)

Name of file : black_sheep.txt

In [4]:

print("File opening mode :",file.mode)

File opening mode : r

In [5]:

print("File closed or not: ", file.closed)

File closed or not: False

The close() method


It is a good practice to always close the file when you are done with it. The close() method of a file object
flushes any unwritten information and closes the file object, after which no more writing can be done. Python
automatically closes a file when the reference object of a file is reassigned to another file.

The general recipe for closing a file with the close() method is given below:

f ile object. close()

Close the text file "black_sheet.txt" .

In [6]:

file.close()

Reading and Writing Files


The file object returned by open() function provides a set of access methods to make reading and
writing of files easier. The file object methods read() , readline() , readlines() and
write() can be used to read and write files.

localhost:8888/nbconvert/html/PHY 3032 Chapter 10A - File Handling in Python 3 .ipynb?download=false 3/19


13/06/2020 PHY 3032 Chapter 10A - File Handling in Python 3

Reading an entire file with the read() method


The read() method reads a string from an open file.

The general recipe for reading an entire file with read() method is given below:

f ile object. read()

The read() method starts reading the file from the beginning, then tries to read as much as possible,
maybe until the end of file.

Open the text file "black_sheet.txt" for reading only.

In [7]:

file = open("black_sheep.txt","r")

Read the entire file "black_sheet.txt" .

In [8]:

print(file.read())

Baa, baa, brown sheep,


Have you any wool?
Yes sir, yes sir,
Three bags full.
One for the master,
One for the dame,
And one for the Old Man,
Who lives down the lane.

Close the text file "black_sheet.txt" .

In [9]:

file.close ()

Reading only parts of a file with read() method


By default the read() method tries to read the the whole text. But you can also specify how many
characters you want to be read from a file. This is done by passing an optional parameter count to the
read() method which specifies the number of bytes to be read from the opened file.

The general recipe for reading only a part of a file with read() method is given below:

f ile object. read([count])

Where the passed optional parameter count is the number of bytes to be read from the opened file.

localhost:8888/nbconvert/html/PHY 3032 Chapter 10A - File Handling in Python 3 .ipynb?download=false 4/19


13/06/2020 PHY 3032 Chapter 10A - File Handling in Python 3

Open the text file "black_sheet.txt" for reading only.

In [10]:

file = open ("black_sheep.txt","r" )

Read only the first 10 bytes of the file "black_sheet.txt" .

In [11]:

print(file.read (10))

Baa, baa,

Close the text file "black_sheet.txt" .

In [12]:

file.close()

Reading lines from files

Reading a single line from a file with readline() method


You can read the contents of a file one line at a time using the readline() method.

Open the text file "black_sheet.txt" for reading only.

In [13]:

file = open("black_sheep.txt","r")

Read one line of the file "black_sheet.txt" .

In [14]:

print(file.readline())

Baa, baa, brown sheep,

Read the next line in the file "black_sheet.txt" .

In [15]:

print(file.readline())

Have you any wool?

localhost:8888/nbconvert/html/PHY 3032 Chapter 10A - File Handling in Python 3 .ipynb?download=false 5/19


13/06/2020 PHY 3032 Chapter 10A - File Handling in Python 3

Read the next two lines in the file "black_sheet.txt" .

In [16]:

print(file.readline())
print(file.readline())

Yes sir, yes sir,

Three bags full.

Read the next 4 lines in the file "black_sheet.txt" .

In [17]:

print(file.readline())
print(file.readline())
print(file.readline())
print(file.readline())

One for the master,

One for the dame,

And one for the Old Man,

Who lives down the lane.

Close the text file "black_sheet.txt" .

In [18]:

file.close()

By looping through the lines of the file, you can read the whole file, line by line:

localhost:8888/nbconvert/html/PHY 3032 Chapter 10A - File Handling in Python 3 .ipynb?download=false 6/19


13/06/2020 PHY 3032 Chapter 10A - File Handling in Python 3

In [19]:

# open a file for reading


file = open("black_sheep.txt","r")

# loop through lines


for line in file:
print(line)

# close file
file.close()

Baa, baa, brown sheep,

Have you any wool?

Yes sir, yes sir,

Three bags full.

One for the master,

One for the dame,

And one for the Old Man,

Who lives down the lane.

Reading multiple lines from a file with readlines()


method
You can read the multiple lines from a file at once using the readlines() method. The readlines()
method returns a list containing each line in the file as a list item.

Open the text file "black_sheet.txt" for reading only.

In [20]:

file = open("black_sheep.txt","r")

Read multiple lines from file "black_sheet.txt" .

In [21]:

print(file.readlines())

['Baa, baa, brown sheep,\n', 'Have you any wool?\n', 'Yes sir, yes
sir,\n', 'Three bags full.\n', 'One for the master,\n', 'One for th
e dame,\n', 'And one for the Old Man,\n', 'Who lives down the lan
e.\n', '\n']

localhost:8888/nbconvert/html/PHY 3032 Chapter 10A - File Handling in Python 3 .ipynb?download=false 7/19


13/06/2020 PHY 3032 Chapter 10A - File Handling in Python 3

Close the text file "black_sheet.txt" .

In [22]:

file.close()

Since the readlines() method returns a list, you can loop through the list items using a for loop. By
looping through the lines of the file, you can read the whole file, line by line.

In [23]:

# open a file
file = open("black_sheep.txt","r")

# store file content in list: lines


lines = file.readlines()

# loop through lines


for line in lines:
print(line)

# close file
file.close()

Baa, baa, brown sheep,

Have you any wool?

Yes sir, yes sir,

Three bags full.

One for the master,

One for the dame,

And one for the Old Man,

Who lives down the lane.

Writing Lines to a file


Writing Lines to an existing file using write() method
To write lines to an existing file, you must add an access parameter to the open() function:

w : write - will overwrite any existing content


a : append - will append to the end of the file

Open the file "black_sheet.txt" and write content to the file:

localhost:8888/nbconvert/html/PHY 3032 Chapter 10A - File Handling in Python 3 .ipynb?download=false 8/19


13/06/2020 PHY 3032 Chapter 10A - File Handling in Python 3

Open the text file "black_sheet.txt" for writing.

In [24]:

file = open("black_sheep.txt", "w")

Write the following 8 lines of text to file "black_sheet.txt" .

In [25]:

file.write("Baa, baa, brown sheep,\n")


file.write("Have you any wool?\n")
file.write("Yes sir, yes sir,\n")
file.write("Three bags full.\n")

file.write("One for the master,\n")


file.write("One for the dame,\n")
file.write("And one for the Old Man,\n")
file.write("Who lives down the lane.\n")

Out[25]:

25

Close the text file "black_sheet.txt" after writing.

In [26]:

file.close()

Open and read the file after writing:

In [27]:

# open file for reading


file = open("black_sheep.txt", "r")

# read files
print(file.read())

# close file
file.close()

Baa, baa, brown sheep,


Have you any wool?
Yes sir, yes sir,
Three bags full.
One for the master,
One for the dame,
And one for the Old Man,
Who lives down the lane.

Open the file "black_sheet.txt" and append content to the file:

localhost:8888/nbconvert/html/PHY 3032 Chapter 10A - File Handling in Python 3 .ipynb?download=false 9/19


13/06/2020 PHY 3032 Chapter 10A - File Handling in Python 3

Open the text file "black_sheet.txt" for writing.

In [28]:

file = open("black_sheep.txt", "a")

Write the following 8 lines of text to end of file "black_sheet.txt" .

In [29]:

file.write("Baa, baa, brown sheep,\n")


file.write("Have you any wool?\n")
file.write("Yes sir, yes sir,\n")
file.write("Three bags full.\n")

file.write("One for the master,\n")


file.write("One for the dame,\n")
file.write("And one for the Old Man,\n")
file.write("Who lives down the lane.\n")

Out[29]:

25

Close the text file "black_sheet.txt" after appending.

In [30]:

file.close()

Open and read the file after appending:

localhost:8888/nbconvert/html/PHY 3032 Chapter 10A - File Handling in Python 3 .ipynb?download=false 10/19


13/06/2020 PHY 3032 Chapter 10A - File Handling in Python 3

In [31]:

# open file for reading


file = open("black_sheep.txt", "r")

# read files
print(file.read())

# close file
file.close()

Baa, baa, brown sheep,


Have you any wool?
Yes sir, yes sir,
Three bags full.
One for the master,
One for the dame,
And one for the Old Man,
Who lives down the lane.
Baa, baa, brown sheep,
Have you any wool?
Yes sir, yes sir,
Three bags full.
One for the master,
One for the dame,
And one for the Old Man,
Who lives down the lane.

Create a New Text File


To create a new file in Python, use the open() function, with one of the following access parameters:

x : create - Creates a file, returns an error if the file exist


a : append - Create a file if the specified file does not exist
w : write - Create a file if the specified file does not exist

Create a file called "twinkle.txt" .

In [34]:

file = open("twinkle.txt", "x")

Open the text file "twinkle.txt" for reading.

In [35]:

file = open("twinkle.txt","r")

Read the entire file "twinkle.txt" .

localhost:8888/nbconvert/html/PHY 3032 Chapter 10A - File Handling in Python 3 .ipynb?download=false 11/19


13/06/2020 PHY 3032 Chapter 10A - File Handling in Python 3

In [36]:

print(file.read())

Close the text file "twinkle.txt" after writing.

In [37]:

file.close()

Create file "twinkle.txt" if it does not exist.

Open the text file "twinkle.txt" for writing.

In [38]:

file = open("twinkle.txt", "w")

Write the following lines of text to end of file "twinkle.txt" .

In [39]:

file.write("Twinkle, twinkle, little star\n")


file.write("How I wonder what you are\n")
file.write("Up above the world so high\n")
file.write("Like a diamond in the sky\n")
file.write("Twinkle, twinkle little star\n")
file.write("How I wonder what you are\n")

file.write("When the blazing sun is gone\n")


file.write("When he nothing shines upon\n")
file.write("Then you show your little light\n")
file.write("Twinkle, twinkle, all the night\n")
file.write("Twinkle, twinkle, little star\n")
file.write("How I wonder what you are")

Out[39]:

25

Close the text file "twinkle.txt" after writing.

In [40]:

file.close()

Read the entire file "twinkle.txt" .

localhost:8888/nbconvert/html/PHY 3032 Chapter 10A - File Handling in Python 3 .ipynb?download=false 12/19


13/06/2020 PHY 3032 Chapter 10A - File Handling in Python 3

In [41]:

# open file for reading


file = open("twinkle.txt", "r")

# read entire file


print(file.read())

# close file
file.close()

Twinkle, twinkle, little star


How I wonder what you are
Up above the world so high
Like a diamond in the sky
Twinkle, twinkle little star
How I wonder what you are
When the blazing sun is gone
When he nothing shines upon
Then you show your little light
Twinkle, twinkle, all the night
Twinkle, twinkle, little star
How I wonder what you are

Create a New CSV File


A common format for storing information in a file is Comma Separated Values (CSV) . A CSV file
contains data separated by a character (usually a comma). Each row represents one record of data. It is
sometimes called a Character Separated Values file because the separating character could be a different
character such as a semi colon

Create a New CSV file with write() method().

Create a filename string.

In [42]:

filename = "nobel_laureates.csv"

Open the "nobel_laureates.csv" for writing.

In [43]:

file = open(filename, mode = "w")

localhost:8888/nbconvert/html/PHY 3032 Chapter 10A - File Handling in Python 3 .ipynb?download=false 13/19


13/06/2020 PHY 3032 Chapter 10A - File Handling in Python 3

In [44]:

file.write("Johannes van der Waals,1837-1923,Dutch\n")


file.write("Lord Rayleigh,1842-1919,British\n")
file.write("Wilhelm Röntgen,1845-1923,German\n")
file.write("Antoine Henri Becquerel,1852-1908,French\n")
file.write("Albert A. Michelson,1852-1931,German-born American\n")
file.write("Hendrik Antoon Lorentz,1853-1928,Dutch\n")
file.write("Heike Kamerlingh-Onnes,1853-1926,Dutch\n")
file.write("Sir Joseph John Thomson,1856-1940,British\n")
file.write("Max Planck,1858-1947,German\n")
file.write("Pierre Curie,1859-1906,French\n")
file.write("Sir William Henry Bragg,1862-1942,British\n")
file.write("Philipp von Lenard,1862-1947,German\n")
file.write("Wilhelm Wien,1864-1928,German\n")
file.write("Pieter Zeeman,1865-1943,Dutch\n")
file.write("Marie Curie,1867-1934,Polish-born French\n")
file.write("Robert Millikan,1868-1953,American\n")
file.write("Charles Wilson,1869-1959,British\n")
file.write("Jean Baptiste Perrin,1870-1942,French\n")
file.write("Lord Ernest Rutherford,1871-1937,New Zealander\n")
file.write("Guglielmo Marconi,1874-1937,Italian\n")
file.write("Johannes Stark,1874-1957,German\n")
file.write("Charles Glover Barkla,1877-1944,British\n")
file.write("Albert Einstein,1879-1955,German-born American\n")
file.write("Otto Hahn,1879-1968,German\n")
file.write("Max von Laue,1879-1960,German\n")
file.write("Sir Owen Richardson,1879-1959,British\n")
file.write("Clinton Joseph Davisson,1881-1958,American\n")
file.write("Max Born,1882-1970,German-born British\n")
file.write("Percy Williams Bridgman,1882-1961,American\n")
file.write("James Franck,1882-1964,German\n")
file.write("Victor Franz Hess,1883-1964,Austrian\n")
file.write("Peter Debye,1884-1966,Dutch-born German\n")

Out[44]:

40

Close the text file "nobel_laureates.csv" after writing.

In [45]:

file.close()

Read the entire file "nobel_laureates.csv" .

localhost:8888/nbconvert/html/PHY 3032 Chapter 10A - File Handling in Python 3 .ipynb?download=false 14/19


13/06/2020 PHY 3032 Chapter 10A - File Handling in Python 3

In [46]:

# open file for reading


file = open("nobel_laureates.csv","r")

# read file
print(file.read())

# close file
file.close()

Johannes van der Waals,1837-1923,Dutch


Lord Rayleigh,1842-1919,British
Wilhelm Röntgen,1845-1923,German
Antoine Henri Becquerel,1852-1908,French
Albert A. Michelson,1852-1931,German-born American
Hendrik Antoon Lorentz,1853-1928,Dutch
Heike Kamerlingh-Onnes,1853-1926,Dutch
Sir Joseph John Thomson,1856-1940,British
Max Planck,1858-1947,German
Pierre Curie,1859-1906,French
Sir William Henry Bragg,1862-1942,British
Philipp von Lenard,1862-1947,German
Wilhelm Wien,1864-1928,German
Pieter Zeeman,1865-1943,Dutch
Marie Curie,1867-1934,Polish-born French
Robert Millikan,1868-1953,American
Charles Wilson,1869-1959,British
Jean Baptiste Perrin,1870-1942,French
Lord Ernest Rutherford,1871-1937,New Zealander
Guglielmo Marconi,1874-1937,Italian
Johannes Stark,1874-1957,German
Charles Glover Barkla,1877-1944,British
Albert Einstein,1879-1955,German-born American
Otto Hahn,1879-1968,German
Max von Laue,1879-1960,German
Sir Owen Richardson,1879-1959,British
Clinton Joseph Davisson,1881-1958,American
Max Born,1882-1970,German-born British
Percy Williams Bridgman,1882-1961,American
James Franck,1882-1964,German
Victor Franz Hess,1883-1964,Austrian
Peter Debye,1884-1966,Dutch-born German

Create a CSV file using lists

Create two lists cars and country

In [47]:

cars = ['bmw', 'audi', 'toyota', 'subaru', "mazda","jeep", "mercedes benz", "fia


t","kia","mahindra","ford","byd"]

country = ["germany","germany","japan","japan", "japan", "usa", "germany", "ital


y", "south korea","india", "usa", "china"]

localhost:8888/nbconvert/html/PHY 3032 Chapter 10A - File Handling in Python 3 .ipynb?download=false 15/19


13/06/2020 PHY 3032 Chapter 10A - File Handling in Python 3

Print the list cars .

In [48]:

print(cars)

['bmw', 'audi', 'toyota', 'subaru', 'mazda', 'jeep', 'mercedes ben


z', 'fiat', 'kia', 'mahindra', 'ford', 'byd']

Print the list country .

In [49]:

print(country)

['germany', 'germany', 'japan', 'japan', 'japan', 'usa', 'germany',


'italy', 'south korea', 'india', 'usa', 'china']

Create filename string cars.csv

In [50]:

filename = "cars.csv"

Check if the sizes of lists "cars" and "country" are the same.

In [51]:

len(cars) == len(country)

Out[51]:

True

Get the length list cars

In [52]:

list_size = len(cars)

Open the "cars.csv" for writing.

In [53]:

file = open(filename,"w")

Write the lines of file "cars.csv" .

localhost:8888/nbconvert/html/PHY 3032 Chapter 10A - File Handling in Python 3 .ipynb?download=false 16/19


13/06/2020 PHY 3032 Chapter 10A - File Handling in Python 3

In [54]:

for item in range(list_size) :


file.write(cars[item] + " , " + country[item] + "\n")

Close the file "cars.csv" after writing.

In [55]:

file.close()

Read the entire file "cars.csv" .

In [56]:

file = open("cars.csv", "r")

# read file
print(file.read())

# close file
file.close()

bmw , germany
audi , germany
toyota , japan
subaru , japan
mazda , japan
jeep , usa
mercedes benz , germany
fiat , italy
kia , south korea
mahindra , india
ford , usa
byd , china

Getting and Changing the position of file


pointer
The tell() method tells your the current position within the file; in other words, the next read or write will
occur at that many bytes from the beginning of the file.

The seek(offset[, from]) method changes the current file position. The offset argument
indicates the number of bytes to be moved. The optional from argument specifies the reference position
from where the bytes are to be moved. If from is set to 0 , it means use the beginning of the file as the
reference position. If from is set to 1 , it means use the current position as the reference position and if it
is set to 2 then the end of the file would be taken as the reference position.

Open the "twinkle.txt" for reading.

localhost:8888/nbconvert/html/PHY 3032 Chapter 10A - File Handling in Python 3 .ipynb?download=false 17/19


13/06/2020 PHY 3032 Chapter 10A - File Handling in Python 3

In [57]:

file = open("twinkle.txt" , "r+" )

Read the first 10 bytes of text in "twinkle.txt" and store then in variable text .

In [58]:

text = file.read(10)

Print out "text" .

In [59]:

print("Read string is : " , text)

Read string is : Twinkle, t

Get the current position of file pointer

In [60]:

position = file.tell()

Print the current position of file pointer

In [61]:

print( "Current file position : " , position)

Current file position : 10

Reposition pointer to beginning of file

In [62]:

position = file.seek(0 ,0)

Read the first 50 bytes of text in "twinkle.txt" and store then in variable text .

In [63]:

text = file.read(50)

Print out "text" .

localhost:8888/nbconvert/html/PHY 3032 Chapter 10A - File Handling in Python 3 .ipynb?download=false 18/19


13/06/2020 PHY 3032 Chapter 10A - File Handling in Python 3

In [64]:

print( "Again read String is : " , text)

Again read String is : Twinkle, twinkle, little star


How I wonder what yo

Close the file "twinkle.txt" .

In [65]:

file.close()

localhost:8888/nbconvert/html/PHY 3032 Chapter 10A - File Handling in Python 3 .ipynb?download=false 19/19

You might also like