We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 10
SIMPLE AND EASY EXPLANATION
+ NOTES PDF
TOPIC
Python File Operations: Reading files, Writing files in python,
Understanding read functions, read(), readline(), readlines()
Understanding write functions, write() and writelines()
g file pointer using seek Programming, using file
Engineering Express Gas
PYTHON PROGRAMMING
Introduction to Python: Python variables, Python basic Operators, Understanding python
blocks. Python Data Types, Declaring and using Numeric data types: int, float etc.
Python Program Flow Control Conditional blocks: if, else and else if, Simple for loops in
python, For loop using ranges, string, list and dictionaries. Use of while loops in python,
Loop manipulation using pass, continue, break and else. Programming using Python
conditional and loop blocks.
Python Complex data types: Using string data type and string operations, Defining list
and list slicing, Use of Tuple data type. String, List and Dictionary, Manipulations Building
blocks of python programs, string manipulation methods, List manipulation. Dictionary
manipulation, Programming using string, list and dictionary in-built functions. Python
Functions, Organizing python codes using functions.
Python File Operations: Reading files, Writing files in python, Understanding read
functions, read(), readline(), readlines(). Understanding write functions, write() and
writelines() Manipulating file pointer using seek Programming, using file operations.
Python packages: Simple programs using the built-in functions of packages matplotlib,
numpy, pandas etc. GUI Programming: Tkinter introduction, Tkinter and
PythonProgramming, Tk Widgets, Tkinter examples. Python programming with IDE.Engineering Express e@
UNIT - 4
PYTHON FILE
What is a file?
1, File is name location on disk to store related information. It is
disk)
2. Since random excess memory is volatile, which loses its data
when computers turned off, we use file for future use of the
data.
used to permanently store data in nonviolent memory.(e.gHard || __
3. When we want to read. From_a right to a file. We need to open!
it first. When we are done, it needs to be closed. So that
i 7 fi f
He i fil Ht i i
| aN @Bebmaertles—— = Ne |
b, Read or write.(Perform operation)
a\dlose thefileNs \ 3 8 IN FOiN Hy
Advantages file handling
|, Versatility
2, Ease to use
3. Portability
4, Flexiblity
S. integration
Disadvantages
|. performance
2. error handling
3. security risks
4. limited file locking
S. resource managementEngineering Express e@
ile?
Python is a built in function open() to open a file, This function
retums a file object, also called a handle, as it used to read or
modify the file accordingly.
1._>>>f=openC“text.txt”) #open file in current directory
2, >>>f=open(“c:/Python33/README txt” )#specifying full path
We can specify the mode while opening a file. In mode, we specify
whether we want to read ‘r write ‘w’ or append ‘a’ to the file. We
also specify if we want to open the file in text mode or binary
|_ mode,
T is ling is mi In
Nn. i mn il
On the other hand, Binary mode returns bites, and this is the mode || _
| to be used when dealing with non text file like image or exe files.
File access modes
MODE DESCRIPTION
‘f | Open a file for reading. (Default)
or truncates the file if it exists.
x Open a file for exclusive creation. If the file already exists,
the operation fails.
w Open a file for writing, Create a new file if it does not exist,|| _
it, Create a new file if it does not exist.
Open for appending at the end of the file without truncating|| _
Y Open in text mode. (Default)
‘b’__| Open in Binary mode.
+ Open a file for updating Creading and writing)Engineering Express e@
Python file mode:
1. f=openC“text.txt”, equivalent to ‘Y or ‘rt’
2, f=open(“text.txt”, ‘w’)# write in text mode
3, f=open(“img.bmp”, ‘r+b’) _ # read and write in binary mode
Unlike other languages, the character ‘a’ does not imply the number
97 until it is in code using ASCII Cor other equivalent encodings.)
Moreover, the default encoding is platform dependent. In windows,
it is, Cpl2S2, But utf- 8 in Linux.
| So we must not also, Rely on the default encoding or else our code |
i i ntly in dit Fe
H d ith files in
recommended to specify the encoding tile.
Feopen(“text.txt”, mode= ‘r, encoding= ‘utf-3’)
How to close a file using python?
When we are doing great operations to the pile, we need to properly
close the file.
Closing a file wil) free up the resources that were tied with the file || _
and is done using python close() method.
Python has a garbage collector to clean up unreferenced object, but || __
we must not rely on it to close the file.
1. FeopenC“text.txt” encoding = ‘utf-3’)
2. #perform file operations
3.f.closeO.Engineering Express e@
This method is not entirely safe if an exception occurs when we are
forming som ions wit ile. The i ith
closing the file.
A Safeway is to use a try..finally block
1, try:
2. f=openC“text.txt” encoding = ‘utf-8’,
3. #perform file operation
4. Finally:
S. F.closeO.
This way we are guaranteed that the file is properly closed, even if
an exception is raised, causing program flow to stop.
| We don’t need to explicitly call the close) method. It is done __|
internally.
|, with openC“text.txt” encoding = ‘utf-8') as fi
2, #perform file operation
How to write to file using python?
In order to write into a file in python, we need to open it in write
‘w’ append ‘a’ or exclusive creation, ‘x’ mode.
We need to be careful with the ‘w’ mode, as it will overwrite into
the file, if it already exist. All previous data are erased.Engineering Express e@
Writing a string or sequence of bites (for binary files) is done using
vit hod, This he f_chare
written to the file.
» 6
1, with openC“text.txt”, ‘w’,encoding = ‘utf-3’) as f:
2. f.writeCmy first file\n”)
3. f.writeCthis file\n\n”)
4. f.writeC“contaiun three lines\n”)
This program will create a new file named ‘text.txt’ If it does not
exist, if it does exist, it_is overwritten.
We must include the Characters ourselves to distinguish different
| times.
driteli
The writelines() method in Python is used to write a list of strings ||__
| toa file, This method does not add newline characters between the |
list items automatically, so one must add them manually if needed.
The writelinesC) method is more efficient than using a write()
method in_a loop.
Syntax: fileObject.writelinesC sequence )
How to read file in python?
To read a file in python, we must open the file in reading mode.
There are various method available for this purpose. We can use the
read( size) method to read in size number of data. If size
parameter is not specified, it reads and returns up to the end of
the file.Engineering Express
» oD
|, >>>f=openC“text.txt”, ‘r encoding = ‘utf-8’)
2,>>>Ffread(4) #read the first 4 data.
3. This?
4. >>>f.read(4) #read the first 4 data
Stsice
6.>>>F,read() #read in the rest till end of file
7. ‘my first file\n this file\ncontains three lines\v’
3.>>>fread() #future reading returns empty string
9?
We can see that the read() method returns new lines as. ‘\n’.
Once the end of file is reached, we get empty string on further
| reading.
Wd ur nt til Ir
imilarly, the tell hod return: re itionC in
number of bytes)
|, >>>f.tellO# get the current file position
2.56
3, >of si 0, ‘ing file cursor to initial position ==
4.0
S. >>>printCf.read())# read the entire file
6. This is my first file
2. This file
8. Contain three lines
We can read a file line-by-line using a for loop .this is both
efficient _and fast
|. >>>for line in f:
2...._ print(line,end=”)Engineering Express @Q
3.
4, This_is_my first fil
S. This file
6. Contain three lines
The lines in the file itself has a newlines character ‘\v’
Moreover, the printQend parameter to avoid two newlines when
printing
Readline
Alternately, we can use readlineCmethid to read individual lines of
li
I, >>>freadline(O
2,‘this is my first file
3, >>>f readline)
4. This file\w.
5S, >>> readlineO.
6. ‘contain three lines\n’
7. >>>f.readlineO.
3°
Lastly, the readline() method returns a list of remaining lines of
the entire file, All these reading methods return empty value when
and of a file EOF is reached.
1, >>>FreadlinesO
2. [This is my first file\n’, ‘This file\v’, ‘contains three
lines\n’]Engineering Express
Python file method:
q
ilabl.
them have been in above examples
Here is the comeplete list of methods in text mode with the a
brief description
Method
close()
detach()
fileno)
flush()
isatty()
read(n)
readable()
readline(n=-1)
|. readlines(n=-1)
seek(of fset, from=SEEK_SET)
seekable()
}- tell()
truncate(size=None)
writable()
| write(s)
writelines(Lines)
Description
Close an open file. It has no effect if the file is already closed.
Separate the underlying binary buffer from the Text 1OBase and return
it
Return an integer number (file descriptor) of the file.
Flush the write buffer of the file stream.
Return True if the file stream is interactive.
Read atmost n characters form the file. Reads till end of file if itis
negative or None.
Returns True if the file stream can be read from,
Read and return one line from the file. Reads in at most n bytes if
specified.
Read and return a list of lines from the file. Reads in at
‘most n bytes/characters if specified.
Change the file position to of fset bytes, in reference to from (start,
current, end).
Returns True if the file stream supports random access.
Returns the current file location.
Resize the file stream to size bytes. If size is not specified, resize to
current location.
Returns True if the file stream can be written to.
Write string s to the file and return the number of characters written.
Write a list of Lines to the file.Engineering Express