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

PythonUnit-4

The document provides an overview of file handling in Python, including the mechanisms for reading from and writing to disk files. It covers different types of data files (text and binary), file access modes, and the steps for opening, reading, writing, and closing files. Additionally, it explains the importance of flushing data to ensure it is written to the file and provides examples of using various file handling functions.

Uploaded by

mr.robot2622
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

PythonUnit-4

The document provides an overview of file handling in Python, including the mechanisms for reading from and writing to disk files. It covers different types of data files (text and binary), file access modes, and the steps for opening, reading, writing, and closing files. Additionally, it explains the importance of flushing data to ensure it is written to the file and provides examples of using various file handling functions.

Uploaded by

mr.robot2622
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

FILE HANDLING

 INTRODUCTION
 DATA FILES
 OPENING AND CLOSING FILES
 READING AND WRITING FILES
 STANDARD INPUT, OUTPUT AND ERROR STREAMS
Bhagvan Krishna Gupta AP CS KIET
Introduction

 FILE HANDLING is a mechanism by which we


can read data of disk files in python program or
write back data from python program to disk
files.
 So far in our python program the standard input
in coming from keyboard an output is going to
monitor i.e. no where data is stored permanent
and entered data is present as long as program is
running BUT file handling allows us to store data
entered through python program permanently in
disk file and later on we can read back the data
Bhagvan Krishna Gupta AP CS KIET
DATA FILES

 It contains data pertaining to a specific


application, for later use. The data files can be
stored in two ways –
 Text File
 Binary File

Bhagvan Krishna Gupta AP CS KIET


Text File

 Text file stores information in ASCII OR


UNICODE character. In text file everything will
be stored as a character for example if data is
“computer” then it will take 8 bytes and if the
data is floating value like 11237.9876 it will take
10 bytes.
 In text file each like is terminated by special
character called EOL. In text file some
translation takes place when this EOL character
is read or written. In python EOL is ‘\n’ or ‘\r’ or
combination of both
Bhagvan Krishna Gupta AP CS KIET
Binary files

 It stores the information in the same format


as in the memory i.e. data is stored according
to its data type so no translation occurs.
 In binary file there is no delimiter for a new
line
 Binary files are faster and easier for a
program to read and write than text files.
 Data in binary files cannot be directly read, it
can be read only through python program for
the same.
Bhagvan Krishna Gupta AP CS KIET
Steps in Data File Handling

1. OPENING FILE
 We should first open the file for read or write by
specifying the name of file and mode.
2. PERFORMING READ/WRITE
 Once the file is opened now we can either read or
write for which file is opened using various functions
available
3. CLOSING FILE
 After performing operation we must close the file
and release the file for other application to use it,
Bhagvan Krishna Gupta AP CS KIET
Opening File

 File can be opened for either – read, write,


append.
SYNTAX:
file_object = open(filename)
Or
file_object = open(filename,mode)

** default mode is “read”


Bhagvan Krishna Gupta AP CS KIET
Opening File

myfile = open(“story.txt”)
here disk file “story.txt” is loaded in
memory and its reference is linked to “myfile”
object, now python program will access
“story.txt” through “myfile” object.
here “story.txt” is present in the same
folder where .py file is stored otherwise if disk
file to work is in another folder we have to give
full path.
Bhagvan Krishna Gupta AP CS KIET
Opening File
myfile = open(“article.txt”,”r”)
here “r” is for read (although it is by default, other
options are “w” for write, “a” for append)

myfile = open(“d:\\mydata\\poem.txt”,”r”)
here we are accessing “poem.txt” file stored in
separate location i.e. d:\mydata folder.
at the time of giving path of file we must use double
backslash(\\) in place of single backslash because in python
single slash is used for escape character and it may cause
problem like if the folder name is “nitin” and we provide path
as d:\nitin\poem.txt then in \nitin “\n” will become escape
character for new line, SO ALWAYS USE DOUBLE
BACKSLASH IN PATH

Bhagvan Krishna Gupta AP CS KIET


Opening File
myfile = open(“d:\\mydata\\poem.txt”,”r”)
another solution of double backslash is
using “r” before the path making the string as
raw string i.e. no special meaning attached to
any character as:
myfile = open(r“d:\mydata\poem.txt”,”r”)

Bhagvan Krishna Gupta AP CS KIET


File Handle

myfile = open(r“d:\mydata\poem.txt”,”r”)

In the above example “myfile” is the file object


or file handle or file pointer holding the
reference of disk file. In python we will access
and manipulate the disk file through this file
handle only.

Bhagvan Krishna Gupta AP CS KIET


File Access Mode
Text Binary File Description Notes
File Mode
Mode
‘r’ ‘rb’ Read only File must exists, otherwise Python raises
I/O errors
‘w’ ‘wb’ Write only If file not exists, file is created
If file exists, python will truncate
existing data and overwrite the file.
‘a’ ‘ab’ Append File is in write mode only, new data will
be added to the end of existing data i.e.
no overwriting. If file not exists it is
created
‘r+’ ‘r+b’ or ‘rb+’ Read and write File must exists otherwise error is raised
Both reading and writing can take place
w+ ‘w+b’ or ‘wb+’ Write and read File is created if not exists, if exists data
will be truncated, both read and write
allowed
‘a+’ ‘a+b’ or ‘ab+’ Write and read Same as above but previous content will
VINOD K UMAR VERMA, PGT(CS),
Bhagvan KVGupta
Krishna OEF AP
KANPUR
CS KIET&
SAC HIN BHARDWAJ, PGT(CS) , KV NO.1 TEZPUR
be retained and both read and write.
Opening and Closing Files:
Until now, you have been reading and writing to the standard input and output. Now
we will see how to play with actual data files.
Python provides basic functions and methods necessary to manipulate files by default.
You can do your most of the file manipulation using a file object.
The open Function:
Before you can read or write a file, you have to open it using Python's built-in
open() function. This function creates a file object which would be utilized to call other
support methods associated with it.
Syntax:
file object = open(file_name [, access_mode][, buffering])

Bhagvan Krishna Gupta AP CS KIET


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).

Bhagvan Krishna Gupta AP CS KIET


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.

Bhagvan Krishna Gupta AP CS KIET


B.Positioning The File
Pointer
letters.txt

B
:
Bhagvan Krishna Gupta AP CS KIET
2.Reading Information
From Files
Typically reading is done within the body of a
loop
Each execution of the loop will read a line from
the file into a string

Format:
for <variable to store a string> in <name of file
variable>:
<Do something with the string read from file>

Example:
for line Bhagvan
in inputFile:
Krishna Gupta AP CS KIET
print(line) # Echo file contents back onscreen
Closing The File

Although a file is automatically closed when


your program ends it is still a good style to
explicitly close your file as soon as the program
is done with it.
What if the program encounters a runtime error and crashes before it
reaches the end? The input file may remain ‘locked’ an inaccessible state
because it’s still open.
Format:
<name of file variable>.close()

Example:
inputFile.close()
Bhagvan Krishna Gupta AP CS KIET
Reading From Files:
Putting It All Together
Name of the online example: grades1.py
Input files: letters.txt or gpa.txt
inputFileName = input("Enter name of input file: ")
inputFile = open(inputFileName, "r")
print("Opening file", inputFileName, " for reading.")

for line in inputFile:


sys.stdout.write(line)

inputFile.close()
print("Completed reading of file", inputFileName)

Bhagvan Krishna Gupta AP CS KIET


Closing file

 As reference of disk file is stored in file handle


so to close we must call the close() function
through the file handle and release the file.

myfile.close()

Note: open function is built-in function used


standalone while close() must be called through file
handle

Bhagvan Krishna Gupta AP CS KIET


Reading from File

 To read from file python provide many functions


like :
 Filehandle.read([n]) : reads and return n bytes,
if n is not specified it reads entire file.
 Filehandle.readline([n]) : reads a line of input.
If n is specified reads at most n bytes. Read bytes
in the form of string ending with line character or
blank string if no more bytes are left for reading.
 Filehandle.readlines(): reads all lines and
returns them in a list
Bhagvan Krishna Gupta AP CS KIET
Example-1: read()
SAMPLE FILE

Bhagvan Krishna Gupta AP CS KIET


Example-2: read()
SAMPLE FILE

Bhagvan Krishna Gupta AP CS KIET


Example-3: readline()
SAMPLE FILE

Bhagvan Krishna Gupta AP CS KIET


Example-3: readline()
SAMPLE FILE

HAVE YOU NOTICED THE DIFFERENCE IN OUTPUT FROM PREVIOUS OUPUT?


Bhagvan Krishna Gupta AP CS KIET
Example-4: reading line bfoyr mlori
en
upe
dateu
ssvii
sitn
:w
gwwr.peyta
hod
n4l
ci
sipn
.ce
om
()
SAMPLE FILE

Bhagvan Krishna Gupta AP CS KIET


Example-5: reading line bfoyr mlori
en
upe
dateu
ssvii
sitn
:w
gwwf.poytr
hon4l
co
sipo
.cp
om

SAMPLE FILE

Bhagvan Krishna Gupta AP CS KIET


Example-6: Calculating size offor mFoirele
updw
ati
et
shvisita
:n
ww
dw.wpyithtohno4custip.cEom
OL
and blank lines
SAMPLE FILE

Bhagvan Krishna Gupta AP CS KIET


Example-7: readlinefs
or more updates visit: www.python4csip.com
()
SAMPLE FILE

Bhagvan Krishna Gupta AP CS KIET


Example-8 & 9: counting size foorfmofreil
upeds
atei
snvisitb
:y
ww
twe.spythaonnd4csnipo.c.om
of lines
SAMPLE FILE

Bhagvan Krishna Gupta AP CS KIET


Questions…

Bhagvan Krishna Gupta AP CS KIET


Writing onto files
 After read operation, let us take an example
of how to write data in disk files. Python
provides functions:
 write ()
 writelines()
 The above functions are called by the file
handle to write desired content.
Name Syntax Description
write() Filehandle.write(str1) Writes string str1 to file referenced
by filehandle
Writelines() Filehandle.writelines(L) Writes all string in List L as lines to
file referenced by filehandle.
Bhagvan Krishna Gupta AP CS KIET
Example-1: write() using “w” mode

Bhagvan Krishna Gupta AP CS KIET


Example-1: write() using “w” mode

Lets run the


same program
again
Bhagvan Krishna Gupta AP CS KIET
Example-1: write() using “w” mode

Now we can observe that while writing data to file using “w” mode the previous
content of existing file will be overwritten and new content will be saved.

If we want to add new data without overwriting the previous content then we
should write using “a” mode i.e. append mode.

Bhagvan Krishna Gupta AP CS KIET


Example-2: write() using “a” mode

New content is
added after previous
content
Bhagvan Krishna Gupta AP CS KIET
Example-3: using writelines()

Bhagvan Krishna Gupta AP CS KIET


Example-4: Writing String as a record
to file

Bhagvan Krishna Gupta AP CS KIET


Example-4: To copy the content of one
file to another file

Bhagvan Krishna Gupta AP CS KIET


flush() function

 When we write any data to file, python hold


everything in buffer (temporary memory) and
pushes it onto actual file later. If you want to
force Python to write the content of buffer
onto storage, you can use flush() function.
 Python automatically flushes the files when
closing them i.e. it will be implicitly called by
the close(), BUT if you want to flush before
closing any file you can use flush()
Bhagvan Krishna Gupta AP CS KIET
Example: working of flush() Nothing is in
the file
temp.txt
Without flush()

When you run the above code, program will


stopped at “Press any key”, for time being
don’t press any key and go to folder where
file “temp.txt” is created an open it to see
what is in the file till now
NOW PRESS ANY KEY….

Now content is stored,


because of close() function
contents are flushed and
Bhagvan Krishna Gupta AP CS KIET pushed in file
Example: working of flush() All contents
before flush()
With flush() are present
in file

When you run the above code, program will


stopped at “Press any key”, for time being
don’t press any key and go to folder where
file “temp.txt” is created an open it to see
what is in the file till now
NOW PRESS ANY KEY….

Rest of the content is


written because of close(),
contents are flushed and
Bhagvan Krishna Gupta AP CS KIET pushed in file.
Removing whitespaces after reading
from file
 read() and readline() reads data from file and
return it in the form of string and readlines()
returns data in the form of list.
 All these read function also read leading and
trailing whitespaces, new line characters. If you
want to remove these characters you can use
functions
 strip() : removes the given character from both ends.
 lstrip(): removes given character from left end
 rstrip(): removes given character from right end
Bhagvan Krishna Gupta AP CS KIET
Example: strip(),lstrip(),
rstrip()

Bhagvan Krishna Gupta AP CS KIET


File Pointer

 Every file maintains a file pointer which tells the


current position in the file where reading and
writing operation will take.
 When we perform any read/write operation two
things happens:
 The operation at the current position of file pointer
 File pointer advances by the specified number of
bytes.

Bhagvan Krishna Gupta AP CS KIET


Example
myfile = open(“ipl.txt”,”r”)

File pointer will be by default at first position i.e. first character

ch = myfile.read(1)
ch will store first character i.e. first character is consumed, and file pointer will
move to next character

Bhagvan Krishna Gupta AP CS KIET


File Modes and Opening position
of file pointer
FILE MODE OPENING POSITION
r, r+, rb, rb+, r+b Beginning of file
w, w+, wb, wb+, w+b Beginning of file (overwrites the file if
file already exists
a, ab, a+, ab+, a+b At the end of file if file exists otherwise
creates a new file

Bhagvan Krishna Gupta AP CS KIET


Standard INPUT, OUTPUT and ERROR STREAM

 Standard Input : Keyboard


 Standard Output : Monitor
 Standard error : Monitor

 Standard Input devices(stdin) reads from


keyboard
 Standard output devices(stdout) display output
on monitor
 Standard error devices(stderr) same as stdout
but normally for errors only.
Bhagvan Krishna Gupta AP CS KIET
Standard INPUT, OUTPUT and ERROR STREAM
 The standard devices are implemented as
files called standard streams in Python and
we can use them by using sys module.
 After importing sys module we can use
standard streams stdin, stdout, stderr

Bhagvan Krishna Gupta AP CS KIET


“with” statement

 Python’s “with” statement for file handling is


very handy when you have two related
operations which you would like to execute as a
pair, with a block of code in between:
with open(filename[, mode]) as filehandle:
file_manipulation_statement
 The advantage of “with” is it will automatically
close the file after nested block of code. It
guarantees to close the file how nested block
exits even if any run time error occurs
Bhagvan Krishna Gupta AP CS KIET
Example

Bhagvan Krishna Gupta AP CS KIET


File Positions:
The tell() method tells you 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 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 and 1 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
Bhagvan Krishna Gupta AP CS KIET
position.
Example:

fo = open("foo.txt", "r+")
str = fo.read(10);
print ("Read String is : ", str )
position = fo.tell();
print ("Current file position : ", position)
position = fo.seek(0, 0);
str = fo.read(10);
print ("Again read String is : ", str)
fo.close()

This would produce following result:


Read String is : Python is
Current file position : 10
Again read String is : Python is

Bhagvan Krishna Gupta AP CS KIET


Renaming and Deleting Files:
Python os module provides methods that help you perform file-processing operations,
such as renaming and deleting files.
To use this module you need to import it first and then you can all any related
functions.
The rename() Method:
The rename() method takes two arguments, the current filename and the
new filename.
Syntax:
import os
os.rename(current_file_name, new_file_name)
Example:
import os
os.rename( "test1.txt", "test2.txt" )

Bhagvan Krishna Gupta AP CS KIET


The delete() Method:
You can use the delete() method to delete files by supplying the name of the
file to be deleted as the argument.
Syntax:
os.remove(file_name)
Example:
import os
os.remove("test2.txt")

Bhagvan Krishna Gupta AP CS KIET


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.
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")

Bhagvan Krishna Gupta AP CS KIET


File Input: Alternate
Implementation
Name of the online example: grades3.py
inputFileName = input ("Enter name of input file: ")
inputFile = open(inputFileName, "r")
print("Opening file", inputFileName, " for reading.")

line = inputFile.readline()

while (line != ""):


sys.stdout.write(line)
line = inputFile.readline()

inputFile.close()
print("Completed reading of file", inputFileName)

Bhagvan Krishna Gupta AP CS KIET


Data Processing: Files

Files can be used to store complex data given


that there exists a predefined format.
Format of the example input file: ‘employees.txt’
<Last name><SP><First Name>,<Occupation>,<Income>

Bhagvan Krishna Gupta AP CS KIET


Example Program:
# EMPLOYEES.TXT
data_processing.py Adama Lee,CAG,30000
Morris Heather,Heroine,0
Lee Bruce,JKD master,100000
inputFile = open ("employees.txt", "r")

print ("Reading from file input.txt")


for line in inputFile:
name,job,income = line.split(',')
last,first = name.split()
income = int(income)
income = income + (income * BONUS)
print("Name: %s, %s\t\t\tJob: %s\t\tIncome $%.2f"
%(first,last,job,income))

print ("Completed reading of file input.txt")


inputFile.close()

Bhagvan Krishna Gupta AP CS KIET


Binary file operations

 If we want to write a structure such as list or


dictionary to a file and read it subsequently
we need to use the Python module pickle.
Pickling is the process of converting structure
to a byte stream before writing to a file and
while reading the content of file a reverse
process called Unpickling is used to convert
the byte stream back to the original format.

Bhagvan Krishna Gupta AP CS KIET


Steps to perform binary file operations

 First we need to import the module called


pickle.
 This module provides 2 main functions:
 dump() : to write the object in file which is loaded
in binary mode
🞍 Syntax : dump(object_to_write, filehandle)

 load() : dumped data can be read from file using


load() i.e. it is used to read object from pickle file.
🞍 Syntax: object = load(filehandle)

Bhagvan Krishna Gupta AP CS KIET


Example: dump()

See the content is some kind


of encrypted format, and it is
not in complete readable
Bhagvan Krishna Gupta AP CS KIET form
Example: load()

Bhagvan Krishna Gupta AP CS KIET


Absolute Vs Relative PATH
 To understand PATH we must be familiar with
the terms: DRIVE, FOLDER/DIRECTORY,
FILES.
 Our hard disk is logically divided into many
parts called DRIVES like C DRIVE, D DRIVE
etc.

Bhagvan Krishna Gupta AP CS KIET


Absolute Vs Relative PATH
 The drive is the main container in which we
put everything to store.
 The naming format is : DRIVE_LETTER:
 For e.g. C: , D:
 Drive is also known as ROOT DIRECTORY.
 Drive contains Folder and Files.
 Folder contains sub-folders or files
 Files are the actual data container.

Bhagvan Krishna Gupta AP CS KIET


Absolute Vs Relative PATH
DRIVE
FOLDER

Bhagvan Krishna Gupta AP CS KIET


DRIVE/FOLDER/FILE HIERARCHY

C:\
DRIV E

SALES IT HR PROD
FOLDE R FOLDE R FOLDE R FOLDE R

2018 2019 MEMBERS.DOC NOIDA DELHI


FOLDE R FOLDE R FOLDE R FOLDE R FOLDE R

REVENUE.TXT SHEET.XLS SEC_8.XLS SEC_12.PPT


FILE FILE FILE FILE

Bhagvan Krishna Gupta AP CS KIET


Absolute Path
 Absolute path is the full address of any file or
folder from the Drive i.e. from ROOT
FOLDER. It is like:
Drive_Name:\Folder\Folder…\filename
 For e.g. the Absolute path of file
REVENUE.TXT will be
 C:\SALES\2018\REVENUE.TXT
 Absolute path of SEC_12.PPT is
 C:\PROD\NOIDA\Sec_12.ppt

Bhagvan Krishna Gupta AP CS KIET


Relative Path

 Relative Path is the location of file/folder


from the current folder. To use Relative path
special symbols are:
 Single Dot ( . ) : single dot ( . ) refers to current
folder.
 Double Dot ( .. ) : double dot ( .. ) refers to parent
folder
 Backslash ( \ ) : first backslash before (.) and
double dot( .. ) refers to ROOT folder.

Bhagvan Krishna Gupta AP CS KIET


Relative addressing
Current working directory
C:\
DRIVE

SALES IT HR PROD
FOLDER FOLDER FOLDER FOLDER

2018 2019 MEMBERS.DOC NOIDA DELHI


FOLDER FOLDER FOLDER FOLDER FOLDER

REVENUE.TXT SHEET.XLS SEC_8.XLS SEC_12.PPT


FILE FILE FILE FILE

SUPPOSE CURRENT WORKING DIRECTORY IS : SALES


WE WANT TO ACCESS SHEET.XLS FILE, THEN RELATIVE ADDRESS WILL BE

.\2019\SHEET.XLS
Bhagvan Krishna Gupta AP CS KIET
Relative addressing
Current working
directory
C:\
DRIVE

SALES IT HR PROD
FOLDER FOLDER FOLDER FOLDER

2018 2019 MEMBERS.DOC NOIDA DELHI


FOLDER FOLDER FOLDER FOLDER FOLDER

REVENUE.TXT SHEET.XLS SEC_8.XLS SEC_12.PPT


FILE FILE FILE FILE

SUPPOSE CURRENT WORKING DIRECTORY IS : DELHI


WE WANT TO ACCESS SEC_8.XLS FILE, THEN RELATIVE ADDRESS WILL BE
..\NOIDA\SEC_8.XLS
Bhagvan Krishna Gupta AP CS KIET
Getting name of current working
directory
import os
pwd = os.getcwd()
print("Current Directory :",pwd)

Bhagvan Krishna Gupta AP CS KIET


File Positions:
The tell() method tells you 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 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 and 1 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.

Bhagvan Krishna Gupta AP CS KIET


Example:

fo = open("foo.txt", "r+")
str = fo.read(10);
print ("Read String is : ", str )
position = fo.tell();
print ("Current file position : ", position)
position = fo.seek(0, 0);
str = fo.read(10);
print ("Again read String is : ", str)
fo.close()
This would produce following result:
Read String is : Python is
Current file position : 10
Again read String is : Python is

Bhagvan Krishna Gupta AP CS KIET


Renaming and Deleting Files:
Python os module provides methods that help you perform file-processing operations,
such as renaming and deleting files.
To use this module you need to import it first and then you can all any related
functions.
The rename() Method:
The rename() method takes two arguments, the current filename and the
new filename.
Syntax:
os.rename(current_file_name, new_file_name)
Example:
import os
os.rename( "test1.txt", "test2.txt" )

Bhagvan Krishna Gupta AP CS KIET


The delete() Method:
You can use the delete() method to delete files by supplying the name of the
file to be deleted as the argument.
Syntax:
os.remove(file_name)
Example:
import os
os.remove("test2.txt")

Bhagvan Krishna Gupta AP CS KIET


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.
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")

Bhagvan Krishna Gupta AP CS KIET


File Input: Alternate
Implementation
Name of the online example: grades3.py
inputFileName = input ("Enter name of input file: ")
inputFile = open(inputFileName, "r")
print("Opening file", inputFileName, " for reading.")

line = inputFile.readline()

while (line != ""):


sys.stdout.write(line)
line = inputFile.readline()

inputFile.close()
print("Completed reading of file", inputFileName)

Bhagvan Krishna Gupta AP CS KIET


Data Processing: Files

Files can be used to store complex data given


that there exists a predefined format.
Format of the example input file: ‘employees.txt’
<Last name><SP><First Name>,<Occupation>,<Income>

Bhagvan Krishna Gupta AP CS KIET


Python File Methods
There are various methods available with the file object. Some of them have been used in the above examples.
Here is the complete list of methods in text mode with a brief description:

Bhagvan Krishna Gupta AP CS KIET


Method Description

close() Closes an opened file. It has no effect if the file is already closed.

detach() Separates the underlying binary buffer from the TextIOBase and returns it.

fileno() Returns an integer number (file descriptor) of the file.

flush() Flushes the write buffer of the file stream.

isatty() Returns True if the file stream is interactive.

Reads at most n characters from the file. Reads till end of file if it is negative
read(n)
or None.

readable() Returns True if the file stream can be read from.

readline(n=-1) Reads and returns one line from the file. Reads in at most n bytes if specified.

Reads and returns a list of lines from the file. Reads in at most n bytes/characters
readlines(n=-1)
if specified.

seek(offset,from=SE
Changes the file position to offset bytes, in reference to from (start, current, end).
EK_SET)

Bhagvan Krishna Gupta AP CS KIET


seekable() Returns True if the file stream supports random access.

tell() Returns the current file location.

Resizes the file stream to size bytes. If size is not


truncate(size=None)
specified, resizes to current location..

writable() Returns True if the file stream can be written to.

Writes the string s to the file and returns the number of


write(s)
characters written..

writelines(lines) Writes a list of lines to the file..

Bhagvan Krishna Gupta AP CS KIET

You might also like