PythonUnit-4
PythonUnit-4
INTRODUCTION
DATA FILES
OPENING AND CLOSING FILES
READING AND WRITING FILES
STANDARD INPUT, OUTPUT AND ERROR STREAMS
Bhagvan Krishna Gupta AP CS KIET
Introduction
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
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
myfile = open(r“d:\mydata\poem.txt”,”r”)
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.
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
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.")
inputFile.close()
print("Completed reading of file", inputFileName)
myfile.close()
SAMPLE FILE
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.
New content is
added after previous
content
Bhagvan Krishna Gupta AP CS KIET
Example-3: using writelines()
ch = myfile.read(1)
ch will store first character i.e. first character is consumed, and file pointer will
move to next character
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()
line = inputFile.readline()
inputFile.close()
print("Completed reading of file", inputFileName)
C:\
DRIV E
SALES IT HR PROD
FOLDE R FOLDE R FOLDE R FOLDE R
SALES IT HR PROD
FOLDER FOLDER FOLDER FOLDER
.\2019\SHEET.XLS
Bhagvan Krishna Gupta AP CS KIET
Relative addressing
Current working
directory
C:\
DRIVE
SALES IT HR PROD
FOLDER FOLDER FOLDER FOLDER
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
line = inputFile.readline()
inputFile.close()
print("Completed reading of file", inputFileName)
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.
Reads at most n characters from the file. Reads till end of file if it is negative
read(n)
or None.
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)