SlideShare a Scribd company logo
1
CHAPTER 7
File Handling
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
2
File
A file is a collection of data stored on a secondary storage device like hard disk.
A file is basically used because real-life applications involve large amounts of data and in such situations the
console oriented I/O operations pose two major problems:
• First, it becomes cumbersome and time consuming to handle huge amount of data through terminals.
• Second, when doing I/O using terminal, the entire data is lost when either the program is terminated or
computer is turned off.Therefore, it becomes necessary to store data on a permanent storage (the disks) and
read whenever necessary, without destroying the data.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
3
File Path
Files that we use are stored on a storage medium like the hard disk in such a way
that they can be easily retrieved as and when required.
Every file is identified by its path that begins from the root node or the root folder.
In Windows, C: (also known as C drive) is the root folder but you can also have a
path that starts from other drives like D:, E:, etc. The file path is also known as
pathname.
Relative Path and Absolute Path
A file path can be either relative or absolute. While an absolute path always contains
the root and the complete directory list to specify the exact location the file, relative
path needs to be combined with another path in order to access a file. It starts with
respect to the current working directory and therefore lacks the leading slashes. For
example, C:StudentsUnder GraduateBTech_CS.docx but Under Graduate
BTech_CS.docx is a relative path as only a part of the complete path is specified.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
4
ASCIIText Files
A text file is a stream of characters that can be sequentially processed by a computer in forward direction. For this
reason a text file is usually opened for only one kind of operation (reading, writing, or appending) at any given time.
Because text files can process characters, they can only read or write data one character at a time. In Python, a text
stream is treated as a special kind of file.
Depending on the requirements of the operating system and on the operation that has to be performed (read/write
operation) on the file, the newline characters may be converted to or from carriage-return/linefeed combinations.
Besides this, other character conversions may also be done to satisfy the storage requirements of the operating
system. However, these conversions occur transparently to process a text file. In a text file, each line contains zero or
more characters and ends with one or more characters
Another important thing is that when a text file is used, there are actually two representations of data- internal or
external. For example, an integer value will be represented as a number that occupies 2 or 4 bytes of memory
internally but externally the integer value will be represented as a string of characters representing its decimal or
hexadecimal value. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
5
Binary Files
A binary file is a file which may contain any type of data, encoded in binary form for computer storage and
processing purposes. It includes files such as word processing documents, PDFs, images, spreadsheets, videos,
zip files and other executable programs. Like a text file, a binary file is a collection of bytes. A binary file is
also referred to as a character stream with following two essential differences.
• A binary file does not require any special processing of the data and each byte of data is transferred to or
from the disk unprocessed.
• Python places no constructs on the file, and it may be read from, or written to, in any manner the
programmer wants.
While text files can be processed sequentially, binary files, on the other hand, can be either processed
sequentially or randomly depending on the needs of the application.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
6
The Open() Function
Before reading from or writing to a file, you must first open it using Python’s built-in open() function.This
function creates a file object, which will be used to invoke methods associated with it.The syntax of open() is:
fileObj = open(file_name [, access_mode])
Here,
file_name is a string value that specifies name of the file that you want to access.
access_mode indicates the mode in which the file has to be opened, i.e., read, write, append, etc.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Example:
7
The open() Function – Access Modes
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
8
The File Object Attributes
Once a file is successfully opened, a file object is returned. Using this file object, you can easily access different
type of information related to that file. This information can be obtained by reading values of specific
attributes of the file.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Example:
9
The close () Method
The close() method is used to close the file object. Once a file object is closed, you cannot further read
from or write into the file associated with the file object.While closing the file object the close() flushes
any unwritten information.Although, Python automatically closes a file when the reference object of a file
is reassigned to another file, but as a good programming habit you should always explicitly use the close()
method to close a file.The syntax of close() is fileObj.close()
The close() method frees up any system resources such as file descriptors, file locks, etc. that are
associated with the file. Moreover, there is an upper limit to the number of files a program can open. If
that limit is exceeded then the program may even crash or work in unexpected manner. Thus, you can
waste lots of memory if you keep many files open unnecessarily and also remember that open files always
stand a chance of corruption and data loss.
Once the file is closed using the close() method, any attempt to use the file object will result in an error.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
10
The write() and writelines() Methods
The write() method is used to write a string to an already opened file. Of course this string may include
numbers, special characters or other symbols. While writing data to a file, you must remember that the
write() method does not add a newline character ('n') to the end of the string.The syntax of write() method
is: fileObj.write(string)
The writelines() method is used to write a list of strings.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Examples:
11
append() Method
Once you have stored some data in a file, you can always open that file again to write more data or append
data to it.To append a file, you must open it using 'a' or 'ab' mode depending on whether it is a text file or a
binary file. Note that if you open a file in 'w' or 'wb' mode and then start writing data into it, then its
existing contents would be overwritten. So always open the file in 'a' or 'ab' mode to add more data to
existing data stored in the file.
Appending data is especially essential when creating a log of events or combining a large set of data into
one file.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Example:
12
The read() and readline() Methods
The read() method is used to read a string from an already opened file.As said before, the string can include,
alphabets, numbers, characters or other symbols.The syntax of read() method is fileObj.read([count])
In the above syntax, count is an optional parameter which if passed to the read() method specifies the
number of bytes to be read from the opened file.The read() method starts reading from the beginning of the
file and if count is missing or has a negative value then, it reads the entire contents of the file (i.e., till the end
of file).
The readlines() method is used to read all the lines in the file
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Example:
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 13
read(n) or filevar.read()
Reads and returns a string of n characters, or the entire file as a single string
if n is not provided.
readline(n) or filevar.readline()
Returns the next line of the file with all text up to and including the newline
character. If n is provided as a parameter than only n characters will be
returned if the line is longer than n.
readlines(n) or filevar.readlines()
Returns a list of strings, each representing a single line of the file. If n is not
provided then all lines of the file are returned. If n is provided
then n characters are read but n is rounded up so that an entire line is
returned.
14
Opening Files using “with” Keyword
It is good programming habit to use the with keyword when working with file objects.This has the advantage
that the file is properly closed after it is used even if an error occurs during read or write operation or even
when you forget to explicitly close the file.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Examples:
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 15
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 16
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 17
with open("q1.py", 'r') as file1:
with open("new.py", 'w') as file2:
i=0
buf=file1.readline()
while (i<len(buf)):
if "#" in buf[i] :
i=i+1
else:
file2.write(buf[i])
i=i+1
print("copied")
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 18
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 19
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 20
21
Splitting Words
Python allows you to read line(s) from a file and splits the line (treated as a string) based on a character. By
default, this character is space but you can even specify any other character to split words in the string.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Example:
22
Some Other Useful File Methods
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
23
File Positions
With every file, the file management system associates a pointer often known as file pointer that facilitate
the movement across the file for reading and/ or writing data.The file pointer specifies a location from where
the current read or write operation is initiated. Once the read/write operation is completed, the pointer is
automatically updated.
Python has various methods that tells or sets the position of the file pointer. For example, the tell() method
tells the current position within the file at which the next read or write operation will occur. It is specified as
number of bytes from the beginning of the file. When you just open a file for reading, the file pointer is
positioned at location 0, which is the beginning of the file.
The seek(offset[, from]) method is used to set the position of the file pointer or in simpler terms, move the
file pointer to a new location.The offset argument indicates the number of bytes to be moved and the from
argument specifies the reference position from where the bytes are to be moved.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
24
File Positions - Example
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
25
Renaming and Deleting Files
The os module in Python has various methods that can be used to perform file-processing operations like
renaming and deleting files.To use the methods defined in the os module, you should first import it in your
program then call any related functions.
The rename() Method: The rename() method takes two arguments, the current filename and the new
filename. Its syntax is: os.rename(old_file_name, new_file_name)
The remove() Method: This method can be used to delete file(s).The method takes a filename (name of the
file to be deleted) as an argument and deletes that file. Its syntax is: os.remove(file_name)
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Examples:
26
Directory Methods
The mkdir() Method: The mkdir()method of the OS module is used to create directories in the current
directory.The method takes the name of the directory (the one to be created) as an argument.The syntax of
mkdir() is, os.mkdir("new_dir_name")
The getcwd() Method:The getcwd() method is used to display the current working directory (cwd).
os.getcwd()
The chdir() Method:The chdir() method is used to change the current directory.The method takes the name
of the directory which you want to make the current directory as an argument. Its syntax is
os.chdir("dir_name")
The rmdir() Method:The rmdir() method is used to remove or delete a directory. For this, it accepts name of
the directory to be deleted as an argument. However, before removing a directory, it should be absolutely
empty and all the contents in it should be removed.The syntax of remove() method is os.rmdir(("dir_name")
The mkdirs() method:The method mkdirs() is used to create more than one folder.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
27
Directory Methods - Examples
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.

More Related Content

Similar to file_handling_python_bca_computer_python (20)

file handling.pdf
file handling.pdffile handling.pdf
file handling.pdf
RonitVaskar2
 
FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
kendriyavidyalayano24
 
Python Files I_O17.pdf
Python Files I_O17.pdfPython Files I_O17.pdf
Python Files I_O17.pdf
RashmiAngane1
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
nitamhaske
 
File handling with python class 12th .pdf
File handling with python class 12th .pdfFile handling with python class 12th .pdf
File handling with python class 12th .pdf
lionsconvent1234
 
Python-FileHandling.pptx
Python-FileHandling.pptxPython-FileHandling.pptx
Python-FileHandling.pptx
Karudaiyar Ganapathy
 
file handling.pptx avlothaan pa thambi popa
file handling.pptx avlothaan pa thambi popafile handling.pptx avlothaan pa thambi popa
file handling.pptx avlothaan pa thambi popa
senniyappanharish
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
22261A1201ABDULMUQTA
 
pspp-rsk.pptx
pspp-rsk.pptxpspp-rsk.pptx
pspp-rsk.pptx
ARYAN552812
 
file handling in python using exception statement
file handling in python using exception statementfile handling in python using exception statement
file handling in python using exception statement
srividhyaarajagopal
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
Raja Ram Dutta
 
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnjlecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
MrProfEsOr1
 
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is hereCHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
sidbhat290907
 
FileHandling2023_Text File.pdf CBSE 2014
FileHandling2023_Text File.pdf CBSE 2014FileHandling2023_Text File.pdf CBSE 2014
FileHandling2023_Text File.pdf CBSE 2014
JAYASURYANSHUPEDDAPA
 
FILE HANDLING IN PYTHON Presentation Computer Science
FILE HANDLING IN PYTHON Presentation Computer ScienceFILE HANDLING IN PYTHON Presentation Computer Science
FILE HANDLING IN PYTHON Presentation Computer Science
HargunKaurGrover
 
01 file handling for class use class pptx
01 file handling for class use class pptx01 file handling for class use class pptx
01 file handling for class use class pptx
PreeTVithule1
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptx
ssuserd0df33
 
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
FILE HANDLING COMPUTER SCIENCE -FILES.pptxFILE HANDLING COMPUTER SCIENCE -FILES.pptx
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
anushasabhapathy76
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
MikialeTesfamariam
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
Koteswari Kasireddy
 
Python Files I_O17.pdf
Python Files I_O17.pdfPython Files I_O17.pdf
Python Files I_O17.pdf
RashmiAngane1
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
nitamhaske
 
File handling with python class 12th .pdf
File handling with python class 12th .pdfFile handling with python class 12th .pdf
File handling with python class 12th .pdf
lionsconvent1234
 
file handling.pptx avlothaan pa thambi popa
file handling.pptx avlothaan pa thambi popafile handling.pptx avlothaan pa thambi popa
file handling.pptx avlothaan pa thambi popa
senniyappanharish
 
file handling in python using exception statement
file handling in python using exception statementfile handling in python using exception statement
file handling in python using exception statement
srividhyaarajagopal
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
Raja Ram Dutta
 
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnjlecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
MrProfEsOr1
 
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is hereCHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
sidbhat290907
 
FileHandling2023_Text File.pdf CBSE 2014
FileHandling2023_Text File.pdf CBSE 2014FileHandling2023_Text File.pdf CBSE 2014
FileHandling2023_Text File.pdf CBSE 2014
JAYASURYANSHUPEDDAPA
 
FILE HANDLING IN PYTHON Presentation Computer Science
FILE HANDLING IN PYTHON Presentation Computer ScienceFILE HANDLING IN PYTHON Presentation Computer Science
FILE HANDLING IN PYTHON Presentation Computer Science
HargunKaurGrover
 
01 file handling for class use class pptx
01 file handling for class use class pptx01 file handling for class use class pptx
01 file handling for class use class pptx
PreeTVithule1
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptx
ssuserd0df33
 
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
FILE HANDLING COMPUTER SCIENCE -FILES.pptxFILE HANDLING COMPUTER SCIENCE -FILES.pptx
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
anushasabhapathy76
 

Recently uploaded (20)

FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptxFINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
kippcam
 
Ppt on the related on the solar power system for electric vehicle engineering
Ppt on the related on the solar power system for electric vehicle engineeringPpt on the related on the solar power system for electric vehicle engineering
Ppt on the related on the solar power system for electric vehicle engineering
ravindrabodke
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptxWeek 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghjfHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
yadavshivank2006
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
IntroSlides-June-GDG-Cloud-Munich community [email protected]
IntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdfIntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdf
IntroSlides-June-GDG-Cloud-Munich community [email protected]
Luiz Carneiro
 
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
ijscai
 
11th International Conference on Data Mining (DaMi 2025)
11th International Conference on Data Mining (DaMi 2025)11th International Conference on Data Mining (DaMi 2025)
11th International Conference on Data Mining (DaMi 2025)
kjim477n
 
Pavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible PavementsPavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible Pavements
Sakthivel M
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
Présentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptxPrésentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptx
KHADIJAESSAKET
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docxNew Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
Airport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptxAirport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptx
BibekMedhi2
 
Structure of OS ppt Structure of OsS ppt
Structure of OS ppt Structure of OsS pptStructure of OS ppt Structure of OsS ppt
Structure of OS ppt Structure of OsS ppt
Wahajch
 
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptxFINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
kippcam
 
Ppt on the related on the solar power system for electric vehicle engineering
Ppt on the related on the solar power system for electric vehicle engineeringPpt on the related on the solar power system for electric vehicle engineering
Ppt on the related on the solar power system for electric vehicle engineering
ravindrabodke
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptxWeek 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghjfHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
yadavshivank2006
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
ijscai
 
11th International Conference on Data Mining (DaMi 2025)
11th International Conference on Data Mining (DaMi 2025)11th International Conference on Data Mining (DaMi 2025)
11th International Conference on Data Mining (DaMi 2025)
kjim477n
 
Pavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible PavementsPavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible Pavements
Sakthivel M
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
Présentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptxPrésentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptx
KHADIJAESSAKET
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docxNew Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
Airport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptxAirport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptx
BibekMedhi2
 
Structure of OS ppt Structure of OsS ppt
Structure of OS ppt Structure of OsS pptStructure of OS ppt Structure of OsS ppt
Structure of OS ppt Structure of OsS ppt
Wahajch
 
Ad

file_handling_python_bca_computer_python

  • 1. 1 CHAPTER 7 File Handling © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 2. 2 File A file is a collection of data stored on a secondary storage device like hard disk. A file is basically used because real-life applications involve large amounts of data and in such situations the console oriented I/O operations pose two major problems: • First, it becomes cumbersome and time consuming to handle huge amount of data through terminals. • Second, when doing I/O using terminal, the entire data is lost when either the program is terminated or computer is turned off.Therefore, it becomes necessary to store data on a permanent storage (the disks) and read whenever necessary, without destroying the data. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 3. 3 File Path Files that we use are stored on a storage medium like the hard disk in such a way that they can be easily retrieved as and when required. Every file is identified by its path that begins from the root node or the root folder. In Windows, C: (also known as C drive) is the root folder but you can also have a path that starts from other drives like D:, E:, etc. The file path is also known as pathname. Relative Path and Absolute Path A file path can be either relative or absolute. While an absolute path always contains the root and the complete directory list to specify the exact location the file, relative path needs to be combined with another path in order to access a file. It starts with respect to the current working directory and therefore lacks the leading slashes. For example, C:StudentsUnder GraduateBTech_CS.docx but Under Graduate BTech_CS.docx is a relative path as only a part of the complete path is specified. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 4. 4 ASCIIText Files A text file is a stream of characters that can be sequentially processed by a computer in forward direction. For this reason a text file is usually opened for only one kind of operation (reading, writing, or appending) at any given time. Because text files can process characters, they can only read or write data one character at a time. In Python, a text stream is treated as a special kind of file. Depending on the requirements of the operating system and on the operation that has to be performed (read/write operation) on the file, the newline characters may be converted to or from carriage-return/linefeed combinations. Besides this, other character conversions may also be done to satisfy the storage requirements of the operating system. However, these conversions occur transparently to process a text file. In a text file, each line contains zero or more characters and ends with one or more characters Another important thing is that when a text file is used, there are actually two representations of data- internal or external. For example, an integer value will be represented as a number that occupies 2 or 4 bytes of memory internally but externally the integer value will be represented as a string of characters representing its decimal or hexadecimal value. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 5. 5 Binary Files A binary file is a file which may contain any type of data, encoded in binary form for computer storage and processing purposes. It includes files such as word processing documents, PDFs, images, spreadsheets, videos, zip files and other executable programs. Like a text file, a binary file is a collection of bytes. A binary file is also referred to as a character stream with following two essential differences. • A binary file does not require any special processing of the data and each byte of data is transferred to or from the disk unprocessed. • Python places no constructs on the file, and it may be read from, or written to, in any manner the programmer wants. While text files can be processed sequentially, binary files, on the other hand, can be either processed sequentially or randomly depending on the needs of the application. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 6. 6 The Open() Function Before reading from or writing to a file, you must first open it using Python’s built-in open() function.This function creates a file object, which will be used to invoke methods associated with it.The syntax of open() is: fileObj = open(file_name [, access_mode]) Here, file_name is a string value that specifies name of the file that you want to access. access_mode indicates the mode in which the file has to be opened, i.e., read, write, append, etc. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Example:
  • 7. 7 The open() Function – Access Modes © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 8. 8 The File Object Attributes Once a file is successfully opened, a file object is returned. Using this file object, you can easily access different type of information related to that file. This information can be obtained by reading values of specific attributes of the file. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Example:
  • 9. 9 The close () Method The close() method is used to close the file object. Once a file object is closed, you cannot further read from or write into the file associated with the file object.While closing the file object the close() flushes any unwritten information.Although, Python automatically closes a file when the reference object of a file is reassigned to another file, but as a good programming habit you should always explicitly use the close() method to close a file.The syntax of close() is fileObj.close() The close() method frees up any system resources such as file descriptors, file locks, etc. that are associated with the file. Moreover, there is an upper limit to the number of files a program can open. If that limit is exceeded then the program may even crash or work in unexpected manner. Thus, you can waste lots of memory if you keep many files open unnecessarily and also remember that open files always stand a chance of corruption and data loss. Once the file is closed using the close() method, any attempt to use the file object will result in an error. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 10. 10 The write() and writelines() Methods The write() method is used to write a string to an already opened file. Of course this string may include numbers, special characters or other symbols. While writing data to a file, you must remember that the write() method does not add a newline character ('n') to the end of the string.The syntax of write() method is: fileObj.write(string) The writelines() method is used to write a list of strings. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Examples:
  • 11. 11 append() Method Once you have stored some data in a file, you can always open that file again to write more data or append data to it.To append a file, you must open it using 'a' or 'ab' mode depending on whether it is a text file or a binary file. Note that if you open a file in 'w' or 'wb' mode and then start writing data into it, then its existing contents would be overwritten. So always open the file in 'a' or 'ab' mode to add more data to existing data stored in the file. Appending data is especially essential when creating a log of events or combining a large set of data into one file. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Example:
  • 12. 12 The read() and readline() Methods The read() method is used to read a string from an already opened file.As said before, the string can include, alphabets, numbers, characters or other symbols.The syntax of read() method is fileObj.read([count]) In the above syntax, count is an optional parameter which if passed to the read() method specifies the number of bytes to be read from the opened file.The read() method starts reading from the beginning of the file and if count is missing or has a negative value then, it reads the entire contents of the file (i.e., till the end of file). The readlines() method is used to read all the lines in the file © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Example:
  • 13. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 13 read(n) or filevar.read() Reads and returns a string of n characters, or the entire file as a single string if n is not provided. readline(n) or filevar.readline() Returns the next line of the file with all text up to and including the newline character. If n is provided as a parameter than only n characters will be returned if the line is longer than n. readlines(n) or filevar.readlines() Returns a list of strings, each representing a single line of the file. If n is not provided then all lines of the file are returned. If n is provided then n characters are read but n is rounded up so that an entire line is returned.
  • 14. 14 Opening Files using “with” Keyword It is good programming habit to use the with keyword when working with file objects.This has the advantage that the file is properly closed after it is used even if an error occurs during read or write operation or even when you forget to explicitly close the file. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Examples:
  • 15. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 15
  • 16. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 16
  • 17. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 17 with open("q1.py", 'r') as file1: with open("new.py", 'w') as file2: i=0 buf=file1.readline() while (i<len(buf)): if "#" in buf[i] : i=i+1 else: file2.write(buf[i]) i=i+1 print("copied")
  • 18. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 18
  • 19. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 19
  • 20. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 20
  • 21. 21 Splitting Words Python allows you to read line(s) from a file and splits the line (treated as a string) based on a character. By default, this character is space but you can even specify any other character to split words in the string. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Example:
  • 22. 22 Some Other Useful File Methods © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 23. 23 File Positions With every file, the file management system associates a pointer often known as file pointer that facilitate the movement across the file for reading and/ or writing data.The file pointer specifies a location from where the current read or write operation is initiated. Once the read/write operation is completed, the pointer is automatically updated. Python has various methods that tells or sets the position of the file pointer. For example, the tell() method tells the current position within the file at which the next read or write operation will occur. It is specified as number of bytes from the beginning of the file. When you just open a file for reading, the file pointer is positioned at location 0, which is the beginning of the file. The seek(offset[, from]) method is used to set the position of the file pointer or in simpler terms, move the file pointer to a new location.The offset argument indicates the number of bytes to be moved and the from argument specifies the reference position from where the bytes are to be moved. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 24. 24 File Positions - Example © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 25. 25 Renaming and Deleting Files The os module in Python has various methods that can be used to perform file-processing operations like renaming and deleting files.To use the methods defined in the os module, you should first import it in your program then call any related functions. The rename() Method: The rename() method takes two arguments, the current filename and the new filename. Its syntax is: os.rename(old_file_name, new_file_name) The remove() Method: This method can be used to delete file(s).The method takes a filename (name of the file to be deleted) as an argument and deletes that file. Its syntax is: os.remove(file_name) © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Examples:
  • 26. 26 Directory Methods The mkdir() Method: The mkdir()method of the OS module is used to create directories in the current directory.The method takes the name of the directory (the one to be created) as an argument.The syntax of mkdir() is, os.mkdir("new_dir_name") The getcwd() Method:The getcwd() method is used to display the current working directory (cwd). os.getcwd() The chdir() Method:The chdir() method is used to change the current directory.The method takes the name of the directory which you want to make the current directory as an argument. Its syntax is os.chdir("dir_name") The rmdir() Method:The rmdir() method is used to remove or delete a directory. For this, it accepts name of the directory to be deleted as an argument. However, before removing a directory, it should be absolutely empty and all the contents in it should be removed.The syntax of remove() method is os.rmdir(("dir_name") The mkdirs() method:The method mkdirs() is used to create more than one folder. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 27. 27 Directory Methods - Examples © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.