SlideShare a Scribd company logo
VKS-LEARNING HUB
PYTHON
VKS-LEARNING HUB
In all the programs we have seen so far, the data provided to a Python program was
through the command line and it is not saved.
If a program has to be run again, the user must again input data.
Similarly, the output of a program appears on the computer screen but is not
saved anywhere permanently.
In practical programming it is necessary to provide data to a program from a file, and
save the output data into a file. The output data may be required for further processing.
A file is a collection of data.
This data may be, for example,
students’ data (Roll No, Name, Address, Tel No, Grades,...),
employee data (EmpID, Name, Dept, Designation, Salary…), etc.
A file could also be used to store a picture audio, video, etc.
Concept of File:
VKS-LEARNING HUB
When a program needs to save data for later
use, it writes the data in a file. The data can be
read from the file at a later time.
What is a file?
A file is a sequence of bytes on the disk/permanent
storage where a group of related data is stored. File is
created for permanent storage of data.
VKS-LEARNING HUB
7-4
Saving data in a file = “writing data to” the file
Output file = file that data is written to
Retrieving data from a file = “reading data from” the file
Input file = file that data is read from
File Access Methods
Two ways to access data stored in files:
• Sequential Access - access data from the beginning
of the file to the end of the
file
• Direct (random) Access- directly access any piece of
data in the file without
reading the data that
Terms
VKS-LEARNING HUB
Types of Files:
(i) Text files - A file whose contents can be viewed using a
text editor is called a text file. A text file is simply a
sequence of ASCII or Unicode characters. Python
programs, contents written in text editors are some of the
example of text files.
(ii) Binary files- A binary file stores the data in the same
way as as stored in the memory. The .exe files,mp3 file,
image files, word documents are some of the examples of
binary files.we can’t read a binary file using a text editor.
VKS-LEARNING HUB
Text file Binary file
Its Bits represent character. Its Bits represent custom Data
Store only plain text in a file. Can store different types of data (audio,
text, image) in a single file
Widely used file format and can be
opened in any text editor.
Developed for an application and can be
opened in that application only.
Mostly .txt and .rtf are used as extensions
to text files.
Can have any application defined
extension.
Text file is human readable because
everything is stored in terms of text.
In binary file everything is written in
terms of 0 and 1, therefore binary file is
not human readable.
Newline(‘n’) & EOF character conversion
takes place
No such character conversion take place
VKS-LEARNING HUB
File handling in Python enables us to create, update,
read, and delete the files stored on the file system
through our python program.
When we want to read from or write to a file we need
to open it first. When we are done, it needs to be
closed, so that resources that are tied with the file are
freed.
Hence, in Python, a file operation takes place in the
following order.
1.Open a file
2.Read or write (perform operation)
3.Close the file
VKS-LEARNING HUB
Opening
 To create any new file then too it must be opened.
 On opening of any file ,a file relevant structure is created in memory as well as
memory space is created to store contents.
Closing
 Once we are done working with the file, we should close the file.
 Closing a file releases valuable system resources.
 In case we forgot to close the file, Python automatically close the file when
program ends or file object is no longer referenced in the program.
However, if our program is large and we are reading or writing multiple files that
can take significant amount of resource on the system.
If we keep opening new files carelessly, we could run out of resources. So be a
good programmer , close the file as soon as all task are done with it.
Opening and Closing Files
VKS-LEARNING HUB
Buffer: transfer of data between RAM and backing storage cannot be
done directly because application (program) has no clue about the backing
storage. It is the OS (Operating System) that controls the backing storage.
Hence the solution is to create a temporary storage in the RAM called
buffer to transfer data between RAM and backing storage.
Writing into a file: data from the variable(s) located in the RAM to be transferred to the
buffer by the Python Program (or any application / program) and data from the buffer to
be transferred to the file located in the backing storage by the OS (Operating System).
Reading from a file: data from file(s) located in the backing storage to be transferred to
the buffer by the OS (Operating System) and data from buffer to be transferred to the
variable(s) located in the RAM by the Python Program (or any application / program).
VKS-LEARNING HUB
Opening a File
General format:
file_variable = open(filename, mode, buffering)
file_variable is the name of the variable that will reference the file object
filename is a string specifying the name of the file
mode is a string specifying the mode (reading, writing, etc.)
Buffering = for no buffering set it to 0.for line buffering set it to 1.if it is
greater than 1 ,then it is buffer size. if it is negative then buffer size is
system default
Python has a built-in function open() to open a file. This function returns a
file object, also called a handle, as it is used to read or modify the file
accordingly. It also create a file if file doesn't exist in write mode
VKS-LEARNING HUB
Python File Modes
Mode Description
'r' Open a file for reading. (default)
'w'
Open a file for writing. Creates a new file if it does not exist or
truncates the file if it exists.
'a' Open for appending at the end of the file without truncating it. Creates
a new file if it does not exist.
't' Open in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and writing)
'x' Open a file for exclusive creation. If the file already exists, the
operation fails.
f = open("test.txt") # equivalent to 'r' or 'rt’
f = open("test.txt",'w') # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode
VKS-LEARNING HUB
The file object attributes:
Once a file is opened and you have one file object, you can get various
information related to that file.
Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.
File.encoding Encoding used for byte string conversion
VKS-LEARNING HUB
7-13
Writing Data to a File
The built-in write() function is used to write data to the file in
the form of string. It does return value of int type which is
the length of string written. Due to buffering, the string may
not actually show up in the file until the flush() or close()
method is called.
The general syntax of write() is:
file_varaible.write(string)
• file_variable – variable that references a file
object
• write - file object used to write data to a file
• string - string that will be written to the file
VKS-LEARNING HUB
VKS-LEARNING HUB
7-15
Writing Data to a File
The file object writelines() method used to write a list of
string or iterable to a file.
The general syntax of writelines() is:
file_varaible.writelines(list)
• file_variable – variable that references a file
object
• writelines - file object method used to write data
to a file
• list - List of Strings
VKS-LEARNING HUB
VKS-LEARNING HUB
File1 = open("filename")
opens the given file for reading, and returns a file object
File1.read() - file's entire contents as a
string
File1.readline() - next line from file as a string
FIle1.readlines() - file's contents as a list of
lines
the lines from a file object can also be read using a for
loop
There are four techniques for reading a file and all these
techniques work by starting at the current file cursor.
Techniques for Reading Files
VKS-LEARNING HUB
1. Using read() method
This techniques is used to:
(i) Read the contents of a file into a ​single string​, or
(ii) To specify exactly how many characters to read.
This reads the entire file from the current cursor location to the end
of the file, and then moves the cursor to the end of the file.
To read the contents of the file into a single string, we use the followi
ng syntax:
<string variable>= <file variable>.read()
VKS-LEARNING HUB
2. Using readlines([size]) method
This technique is used to read ​each line​of a text file and store it in a​
separate​string in a list. After reading the lines, the cursor moves to the
end of the file.
Each line ends with the newline character ‘n’ is a part of string.
To read the contents of the file into a single string, we use the following synt
ax:
<string variable>= <file variable>.readlines([size])
VKS-LEARNING HUB
3. Using readline([size]) method
Read no of characters from file if size is mentioned till
Otherwise reads till new line character.
returns empty string on EOF.
This technique is used to read ​one line​of a text file including the newline character
To read the contents of the single line, we use the following syntax:
<string variable>= <file variable>.readline([size])
VKS-LEARNING HUB
This techniques is used to carry out the same action on each line of a file.
4. Using for x in file loop method
• A file handle open for read can be treated as a sequence of strings where
each line in the file is a string in the sequence
• We can use the for statement to iterate through a sequence
Ad

More Related Content

Similar to VKS-Python-FIe Handling text CSV Binary.pptx (20)

File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnjlecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
MrProfEsOr1
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
nitamhaske
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
Vineeta Garg
 
FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
kendriyavidyalayano24
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptx
AmitKaur17
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing files
keeeerty
 
Data file handling in python introduction,opening &amp; closing files
Data file handling in python introduction,opening &amp; closing filesData file handling in python introduction,opening &amp; closing files
Data file handling in python introduction,opening &amp; closing files
Keerty Smile
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
armaansohail9356
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
MikialeTesfamariam
 
Unit 5 File handling in C programming.pdf
Unit 5 File handling in C programming.pdfUnit 5 File handling in C programming.pdf
Unit 5 File handling in C programming.pdf
SomyaPachauri1
 
File Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingFile Management and manipulation in C++ Programming
File Management and manipulation in C++ Programming
ChereLemma2
 
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 HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.
ssuser00ad4e
 
File Handling
File HandlingFile Handling
File Handling
TusharBatra27
 
Python-files
Python-filesPython-files
Python-files
Krishna Nanda
 
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
 
Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9
AbdulghafarStanikzai
 
File Handling
File HandlingFile Handling
File Handling
AlgeronTongdoTopi
 
File Handling
File HandlingFile Handling
File Handling
AlgeronTongdoTopi
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnjlecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
MrProfEsOr1
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
nitamhaske
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
Vineeta Garg
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptx
AmitKaur17
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing files
keeeerty
 
Data file handling in python introduction,opening &amp; closing files
Data file handling in python introduction,opening &amp; closing filesData file handling in python introduction,opening &amp; closing files
Data file handling in python introduction,opening &amp; closing files
Keerty Smile
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
armaansohail9356
 
Unit 5 File handling in C programming.pdf
Unit 5 File handling in C programming.pdfUnit 5 File handling in C programming.pdf
Unit 5 File handling in C programming.pdf
SomyaPachauri1
 
File Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingFile Management and manipulation in C++ Programming
File Management and manipulation in C++ Programming
ChereLemma2
 
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 HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.
ssuser00ad4e
 
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
 

More from Vinod Srivastava (9)

Understanding Queue in Python using list 2019.pptx
Understanding Queue in Python using list 2019.pptxUnderstanding Queue in Python using list 2019.pptx
Understanding Queue in Python using list 2019.pptx
Vinod Srivastava
 
Introduction to Python loops while and for .pptx
Introduction to Python loops while and for .pptxIntroduction to Python loops while and for .pptx
Introduction to Python loops while and for .pptx
Vinod Srivastava
 
VKS-Python Basics for Beginners and advance.pptx
VKS-Python Basics for Beginners and advance.pptxVKS-Python Basics for Beginners and advance.pptx
VKS-Python Basics for Beginners and advance.pptx
Vinod Srivastava
 
Python Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-FinallyPython Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-Finally
Vinod Srivastava
 
Javascripting.pptx
Javascripting.pptxJavascripting.pptx
Javascripting.pptx
Vinod Srivastava
 
python-strings.pptx
python-strings.pptxpython-strings.pptx
python-strings.pptx
Vinod Srivastava
 
Vks python
Vks pythonVks python
Vks python
Vinod Srivastava
 
User documentationinter
User documentationinterUser documentationinter
User documentationinter
Vinod Srivastava
 
Graphics sw
Graphics swGraphics sw
Graphics sw
Vinod Srivastava
 
Understanding Queue in Python using list 2019.pptx
Understanding Queue in Python using list 2019.pptxUnderstanding Queue in Python using list 2019.pptx
Understanding Queue in Python using list 2019.pptx
Vinod Srivastava
 
Introduction to Python loops while and for .pptx
Introduction to Python loops while and for .pptxIntroduction to Python loops while and for .pptx
Introduction to Python loops while and for .pptx
Vinod Srivastava
 
VKS-Python Basics for Beginners and advance.pptx
VKS-Python Basics for Beginners and advance.pptxVKS-Python Basics for Beginners and advance.pptx
VKS-Python Basics for Beginners and advance.pptx
Vinod Srivastava
 
Python Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-FinallyPython Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-Finally
Vinod Srivastava
 
Ad

Recently uploaded (20)

Introduction to systems thinking tools_Eng.pdf
Introduction to systems thinking tools_Eng.pdfIntroduction to systems thinking tools_Eng.pdf
Introduction to systems thinking tools_Eng.pdf
AbdurahmanAbd
 
L1_Slides_Foundational Concepts_508.pptx
L1_Slides_Foundational Concepts_508.pptxL1_Slides_Foundational Concepts_508.pptx
L1_Slides_Foundational Concepts_508.pptx
38NoopurPatel
 
文凭证书美国SDSU文凭圣地亚哥州立大学学生证学历认证查询
文凭证书美国SDSU文凭圣地亚哥州立大学学生证学历认证查询文凭证书美国SDSU文凭圣地亚哥州立大学学生证学历认证查询
文凭证书美国SDSU文凭圣地亚哥州立大学学生证学历认证查询
Taqyea
 
Analysis of Billboards hot 100 toop five hit makers on the chart.docx
Analysis of Billboards hot 100 toop five hit makers on the chart.docxAnalysis of Billboards hot 100 toop five hit makers on the chart.docx
Analysis of Billboards hot 100 toop five hit makers on the chart.docx
hershtara1
 
AI ------------------------------ W1L2.pptx
AI ------------------------------ W1L2.pptxAI ------------------------------ W1L2.pptx
AI ------------------------------ W1L2.pptx
AyeshaJalil6
 
Fundamentals of Data Analysis, its types, tools, algorithms
Fundamentals of Data Analysis, its types, tools, algorithmsFundamentals of Data Analysis, its types, tools, algorithms
Fundamentals of Data Analysis, its types, tools, algorithms
priyaiyerkbcsc
 
2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry
2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry
2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry
bastakwyry
 
Understanding Complex Development Processes
Understanding Complex Development ProcessesUnderstanding Complex Development Processes
Understanding Complex Development Processes
Process mining Evangelist
 
Process Mining at Deutsche Bank - Journey
Process Mining at Deutsche Bank - JourneyProcess Mining at Deutsche Bank - Journey
Process Mining at Deutsche Bank - Journey
Process mining Evangelist
 
录取通知书加拿大TMU毕业证多伦多都会大学电子版毕业证成绩单
录取通知书加拿大TMU毕业证多伦多都会大学电子版毕业证成绩单录取通知书加拿大TMU毕业证多伦多都会大学电子版毕业证成绩单
录取通知书加拿大TMU毕业证多伦多都会大学电子版毕业证成绩单
Taqyea
 
Controlling Financial Processes at a Municipality
Controlling Financial Processes at a MunicipalityControlling Financial Processes at a Municipality
Controlling Financial Processes at a Municipality
Process mining Evangelist
 
Ann Naser Nabil- Data Scientist Portfolio.pdf
Ann Naser Nabil- Data Scientist Portfolio.pdfAnn Naser Nabil- Data Scientist Portfolio.pdf
Ann Naser Nabil- Data Scientist Portfolio.pdf
আন্ নাসের নাবিল
 
Z14_IBM__APL_by_Christian_Demmer_IBM.pdf
Z14_IBM__APL_by_Christian_Demmer_IBM.pdfZ14_IBM__APL_by_Christian_Demmer_IBM.pdf
Z14_IBM__APL_by_Christian_Demmer_IBM.pdf
Fariborz Seyedloo
 
AWS-Certified-ML-Engineer-Associate-Slides.pdf
AWS-Certified-ML-Engineer-Associate-Slides.pdfAWS-Certified-ML-Engineer-Associate-Slides.pdf
AWS-Certified-ML-Engineer-Associate-Slides.pdf
philsparkshome
 
AWS RDS Presentation to make concepts easy.pptx
AWS RDS Presentation to make concepts easy.pptxAWS RDS Presentation to make concepts easy.pptx
AWS RDS Presentation to make concepts easy.pptx
bharatkumarbhojwani
 
Mining a Global Trade Process with Data Science - Microsoft
Mining a Global Trade Process with Data Science - MicrosoftMining a Global Trade Process with Data Science - Microsoft
Mining a Global Trade Process with Data Science - Microsoft
Process mining Evangelist
 
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
disnakertransjabarda
 
2024 Digital Equity Accelerator Report.pdf
2024 Digital Equity Accelerator Report.pdf2024 Digital Equity Accelerator Report.pdf
2024 Digital Equity Accelerator Report.pdf
dominikamizerska1
 
national income & related aggregates (1)(1).pptx
national income & related aggregates (1)(1).pptxnational income & related aggregates (1)(1).pptx
national income & related aggregates (1)(1).pptx
j2492618
 
What is ETL? Difference between ETL and ELT?.pdf
What is ETL? Difference between ETL and ELT?.pdfWhat is ETL? Difference between ETL and ELT?.pdf
What is ETL? Difference between ETL and ELT?.pdf
SaikatBasu37
 
Introduction to systems thinking tools_Eng.pdf
Introduction to systems thinking tools_Eng.pdfIntroduction to systems thinking tools_Eng.pdf
Introduction to systems thinking tools_Eng.pdf
AbdurahmanAbd
 
L1_Slides_Foundational Concepts_508.pptx
L1_Slides_Foundational Concepts_508.pptxL1_Slides_Foundational Concepts_508.pptx
L1_Slides_Foundational Concepts_508.pptx
38NoopurPatel
 
文凭证书美国SDSU文凭圣地亚哥州立大学学生证学历认证查询
文凭证书美国SDSU文凭圣地亚哥州立大学学生证学历认证查询文凭证书美国SDSU文凭圣地亚哥州立大学学生证学历认证查询
文凭证书美国SDSU文凭圣地亚哥州立大学学生证学历认证查询
Taqyea
 
Analysis of Billboards hot 100 toop five hit makers on the chart.docx
Analysis of Billboards hot 100 toop five hit makers on the chart.docxAnalysis of Billboards hot 100 toop five hit makers on the chart.docx
Analysis of Billboards hot 100 toop five hit makers on the chart.docx
hershtara1
 
AI ------------------------------ W1L2.pptx
AI ------------------------------ W1L2.pptxAI ------------------------------ W1L2.pptx
AI ------------------------------ W1L2.pptx
AyeshaJalil6
 
Fundamentals of Data Analysis, its types, tools, algorithms
Fundamentals of Data Analysis, its types, tools, algorithmsFundamentals of Data Analysis, its types, tools, algorithms
Fundamentals of Data Analysis, its types, tools, algorithms
priyaiyerkbcsc
 
2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry
2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry
2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry
bastakwyry
 
录取通知书加拿大TMU毕业证多伦多都会大学电子版毕业证成绩单
录取通知书加拿大TMU毕业证多伦多都会大学电子版毕业证成绩单录取通知书加拿大TMU毕业证多伦多都会大学电子版毕业证成绩单
录取通知书加拿大TMU毕业证多伦多都会大学电子版毕业证成绩单
Taqyea
 
Controlling Financial Processes at a Municipality
Controlling Financial Processes at a MunicipalityControlling Financial Processes at a Municipality
Controlling Financial Processes at a Municipality
Process mining Evangelist
 
Z14_IBM__APL_by_Christian_Demmer_IBM.pdf
Z14_IBM__APL_by_Christian_Demmer_IBM.pdfZ14_IBM__APL_by_Christian_Demmer_IBM.pdf
Z14_IBM__APL_by_Christian_Demmer_IBM.pdf
Fariborz Seyedloo
 
AWS-Certified-ML-Engineer-Associate-Slides.pdf
AWS-Certified-ML-Engineer-Associate-Slides.pdfAWS-Certified-ML-Engineer-Associate-Slides.pdf
AWS-Certified-ML-Engineer-Associate-Slides.pdf
philsparkshome
 
AWS RDS Presentation to make concepts easy.pptx
AWS RDS Presentation to make concepts easy.pptxAWS RDS Presentation to make concepts easy.pptx
AWS RDS Presentation to make concepts easy.pptx
bharatkumarbhojwani
 
Mining a Global Trade Process with Data Science - Microsoft
Mining a Global Trade Process with Data Science - MicrosoftMining a Global Trade Process with Data Science - Microsoft
Mining a Global Trade Process with Data Science - Microsoft
Process mining Evangelist
 
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
disnakertransjabarda
 
2024 Digital Equity Accelerator Report.pdf
2024 Digital Equity Accelerator Report.pdf2024 Digital Equity Accelerator Report.pdf
2024 Digital Equity Accelerator Report.pdf
dominikamizerska1
 
national income & related aggregates (1)(1).pptx
national income & related aggregates (1)(1).pptxnational income & related aggregates (1)(1).pptx
national income & related aggregates (1)(1).pptx
j2492618
 
What is ETL? Difference between ETL and ELT?.pdf
What is ETL? Difference between ETL and ELT?.pdfWhat is ETL? Difference between ETL and ELT?.pdf
What is ETL? Difference between ETL and ELT?.pdf
SaikatBasu37
 
Ad

VKS-Python-FIe Handling text CSV Binary.pptx

  • 2. VKS-LEARNING HUB In all the programs we have seen so far, the data provided to a Python program was through the command line and it is not saved. If a program has to be run again, the user must again input data. Similarly, the output of a program appears on the computer screen but is not saved anywhere permanently. In practical programming it is necessary to provide data to a program from a file, and save the output data into a file. The output data may be required for further processing. A file is a collection of data. This data may be, for example, students’ data (Roll No, Name, Address, Tel No, Grades,...), employee data (EmpID, Name, Dept, Designation, Salary…), etc. A file could also be used to store a picture audio, video, etc. Concept of File:
  • 3. VKS-LEARNING HUB When a program needs to save data for later use, it writes the data in a file. The data can be read from the file at a later time. What is a file? A file is a sequence of bytes on the disk/permanent storage where a group of related data is stored. File is created for permanent storage of data.
  • 4. VKS-LEARNING HUB 7-4 Saving data in a file = “writing data to” the file Output file = file that data is written to Retrieving data from a file = “reading data from” the file Input file = file that data is read from File Access Methods Two ways to access data stored in files: • Sequential Access - access data from the beginning of the file to the end of the file • Direct (random) Access- directly access any piece of data in the file without reading the data that Terms
  • 5. VKS-LEARNING HUB Types of Files: (i) Text files - A file whose contents can be viewed using a text editor is called a text file. A text file is simply a sequence of ASCII or Unicode characters. Python programs, contents written in text editors are some of the example of text files. (ii) Binary files- A binary file stores the data in the same way as as stored in the memory. The .exe files,mp3 file, image files, word documents are some of the examples of binary files.we can’t read a binary file using a text editor.
  • 6. VKS-LEARNING HUB Text file Binary file Its Bits represent character. Its Bits represent custom Data Store only plain text in a file. Can store different types of data (audio, text, image) in a single file Widely used file format and can be opened in any text editor. Developed for an application and can be opened in that application only. Mostly .txt and .rtf are used as extensions to text files. Can have any application defined extension. Text file is human readable because everything is stored in terms of text. In binary file everything is written in terms of 0 and 1, therefore binary file is not human readable. Newline(‘n’) & EOF character conversion takes place No such character conversion take place
  • 7. VKS-LEARNING HUB File handling in Python enables us to create, update, read, and delete the files stored on the file system through our python program. When we want to read from or write to a file we need to open it first. When we are done, it needs to be closed, so that resources that are tied with the file are freed. Hence, in Python, a file operation takes place in the following order. 1.Open a file 2.Read or write (perform operation) 3.Close the file
  • 8. VKS-LEARNING HUB Opening  To create any new file then too it must be opened.  On opening of any file ,a file relevant structure is created in memory as well as memory space is created to store contents. Closing  Once we are done working with the file, we should close the file.  Closing a file releases valuable system resources.  In case we forgot to close the file, Python automatically close the file when program ends or file object is no longer referenced in the program. However, if our program is large and we are reading or writing multiple files that can take significant amount of resource on the system. If we keep opening new files carelessly, we could run out of resources. So be a good programmer , close the file as soon as all task are done with it. Opening and Closing Files
  • 9. VKS-LEARNING HUB Buffer: transfer of data between RAM and backing storage cannot be done directly because application (program) has no clue about the backing storage. It is the OS (Operating System) that controls the backing storage. Hence the solution is to create a temporary storage in the RAM called buffer to transfer data between RAM and backing storage. Writing into a file: data from the variable(s) located in the RAM to be transferred to the buffer by the Python Program (or any application / program) and data from the buffer to be transferred to the file located in the backing storage by the OS (Operating System). Reading from a file: data from file(s) located in the backing storage to be transferred to the buffer by the OS (Operating System) and data from buffer to be transferred to the variable(s) located in the RAM by the Python Program (or any application / program).
  • 10. VKS-LEARNING HUB Opening a File General format: file_variable = open(filename, mode, buffering) file_variable is the name of the variable that will reference the file object filename is a string specifying the name of the file mode is a string specifying the mode (reading, writing, etc.) Buffering = for no buffering set it to 0.for line buffering set it to 1.if it is greater than 1 ,then it is buffer size. if it is negative then buffer size is system default Python has a built-in function open() to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly. It also create a file if file doesn't exist in write mode
  • 11. VKS-LEARNING HUB Python File Modes Mode Description 'r' Open a file for reading. (default) 'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists. 'a' Open for appending at the end of the file without truncating it. Creates a new file if it does not exist. 't' Open in text mode. (default) 'b' Open in binary mode. '+' Open a file for updating (reading and writing) 'x' Open a file for exclusive creation. If the file already exists, the operation fails. f = open("test.txt") # equivalent to 'r' or 'rt’ f = open("test.txt",'w') # write in text mode f = open("img.bmp",'r+b') # read and write in binary mode
  • 12. VKS-LEARNING HUB The file object attributes: Once a file is opened and you have one file object, you can get various information related to that file. Attribute Description file.closed Returns true if file is closed, false otherwise. file.mode Returns access mode with which file was opened. file.name Returns name of the file. File.encoding Encoding used for byte string conversion
  • 13. VKS-LEARNING HUB 7-13 Writing Data to a File The built-in write() function is used to write data to the file in the form of string. It does return value of int type which is the length of string written. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called. The general syntax of write() is: file_varaible.write(string) • file_variable – variable that references a file object • write - file object used to write data to a file • string - string that will be written to the file
  • 15. VKS-LEARNING HUB 7-15 Writing Data to a File The file object writelines() method used to write a list of string or iterable to a file. The general syntax of writelines() is: file_varaible.writelines(list) • file_variable – variable that references a file object • writelines - file object method used to write data to a file • list - List of Strings
  • 17. VKS-LEARNING HUB File1 = open("filename") opens the given file for reading, and returns a file object File1.read() - file's entire contents as a string File1.readline() - next line from file as a string FIle1.readlines() - file's contents as a list of lines the lines from a file object can also be read using a for loop There are four techniques for reading a file and all these techniques work by starting at the current file cursor. Techniques for Reading Files
  • 18. VKS-LEARNING HUB 1. Using read() method This techniques is used to: (i) Read the contents of a file into a ​single string​, or (ii) To specify exactly how many characters to read. This reads the entire file from the current cursor location to the end of the file, and then moves the cursor to the end of the file. To read the contents of the file into a single string, we use the followi ng syntax: <string variable>= <file variable>.read()
  • 19. VKS-LEARNING HUB 2. Using readlines([size]) method This technique is used to read ​each line​of a text file and store it in a​ separate​string in a list. After reading the lines, the cursor moves to the end of the file. Each line ends with the newline character ‘n’ is a part of string. To read the contents of the file into a single string, we use the following synt ax: <string variable>= <file variable>.readlines([size])
  • 20. VKS-LEARNING HUB 3. Using readline([size]) method Read no of characters from file if size is mentioned till Otherwise reads till new line character. returns empty string on EOF. This technique is used to read ​one line​of a text file including the newline character To read the contents of the single line, we use the following syntax: <string variable>= <file variable>.readline([size])
  • 21. VKS-LEARNING HUB This techniques is used to carry out the same action on each line of a file. 4. Using for x in file loop method • A file handle open for read can be treated as a sequence of strings where each line in the file is a string in the sequence • We can use the for statement to iterate through a sequence
  翻译: