SlideShare a Scribd company logo
1 of 11
File Handling
in Python
Introduction
File handling is the process of reading and
manipulating data from files.
In Python, file handling is a fundamental skill for
working with external data.
Python provides a rich set of built-in functions to
manage files.
Use cases: storing program data, user
configurations, logs, and exchanging data with
other systems.
We will delve into the essentials of file handling
using Python. We'll cover concepts such as opening
and closing files, reading data, writing content, and
different file modes. By the end, you'll have a solid
foundation for working with files effectively in your
Python projects.
Opening and
Closing Files
Use the open() function to open a file:
file_object = open("filename", "mode")
Common file modes: 'r' (read), 'w' (write),
'a' (append), 'x' (create)
Create new files if they don't exist (with 'w'
or 'x')
Always close files with file_object.close()
The open() function is the gateway to file
operations in Python. It creates a file
object that offers methods to interact with
the file. The mode determines your level of
access (read, write, etc). Closing files using
close() releases system resources and
prevents data corruption.
Reading Data from
Files
The read() method returns the entire content as a string.
The readline() method reads a single line at a time.
The readlines() method reads all lines into a list of strings.
Iterate over files using a for loop for line-by-line
processing.
Once a file is open in read mode, you have a variety of
options to extract data. Choose the method best suited to
your task—reading everything at once or working with
lines individually. Looping through files allows you to
process information systematically.
Writing Data to Files
Use the write() method to write a string to a file (mode 'w'
or 'a').
'w' mode overwrites existing content, 'a' mode appends to
the end.
Be careful about overwriting important files.
writelines() can write a list of strings to a file.
Files allow you to make your program's data persistent.
The write() method is your primary tool for saving data to
files. Manage how you modify existing files carefully, using
either 'w' for overwrites or 'a' to add new content.
File Modes
'r' (read): Open for reading (default). Raises an error if the
file doesn't exist.
'w' (write): Open for writing, overwrites existing content,
or creates a new file.
'x' (create): Creates a new file, fails if the file exists.
'a' (append): Open for writing, appends to the end, or
creates if it doesn't exist.
'b' (binary): Used for binary files (images, videos)
**'+' (update): ** For both reading and writing.
These file modes give you granular control over how you
interact with files. Choose the appropriate mode based
on whether you need to read existing data, create new
data, or update file contents.
Working with CSV Files
CSV (Comma-Separated Values) stores structured data in plain text.
Use Python's csv module for handling CSV files.
Import the module: import csv
Use csv.reader() to read CSV data into rows.
Use csv.writer() to write data into CSV format.
CSV is a common format for storing tabular data. Python's csv module
provides tools to easily read from and write data to CSV files, making it
a great choice for interchanging data between systems.
File Path
Management
Use the os module for file path operations.
os.path.exists() checks if a file or directory exists.
os.path.join() combines path components correctly.
os.path.split() separates the filename from the path.
Employ relative and absolute paths for file
references.
Organizing files and directories is crucial in larger
projects. The os module helps navigate your file
system—checking if files exist, constructing paths
properly, and understanding file locations within
your project structure.
Error Handling
Wrap file operations in try-except blocks.
Common file-related exceptions:
FileNotFoundError
IOError
PermissionError
Provide meaningful error messages to the user.
Ensure files are closed properly with a finally block
Files are external resources; things can go wrong (missing files, permissions). Error handling
with try-except makes your Python code robust and allows you to provide informative
error messages if file operations fail.
Conclusion Other Libraries: Explore libraries like pandas for
advanced data manipulation.
Binary Files: Learn about working with non-text
data (images, audio, etc.)
Context Managers: Use the with statement for
more elegant file handling (with open(...) as
file_object).
File Handling Best Practices: Emphasize the
importance of file handling in data-driven
Python projects.
These additional points hint at the broader world
of file handling. Python offers a rich ecosystem
of tools for data-related tasks, allowing you to
work with various file formats. Wrap-up the
presentation by reiterating the importance of file
handling as a fundamental building block for
many Python applications.
What are Python basics?
For Query Contact : 998874-1983

More Related Content

Similar to what are python basics.pptx.Join Python training in Chandigarh

Similar to what are python basics.pptx.Join Python training in Chandigarh (20)

Python-files
Python-filesPython-files
Python-files
 
File Handling
File HandlingFile Handling
File Handling
 
Python files / directories part15
Python files / directories  part15Python files / directories  part15
Python files / directories part15
 
File handling3.pdf
File handling3.pdfFile handling3.pdf
File handling3.pdf
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
 
Python file handling
Python file handlingPython file handling
Python file handling
 
Switching & Multiplexing
Switching & MultiplexingSwitching & Multiplexing
Switching & Multiplexing
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
 
pspp-rsk.pptx
pspp-rsk.pptxpspp-rsk.pptx
pspp-rsk.pptx
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
Data file handling
Data file handlingData file handling
Data file handling
 
Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
 
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
 
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
 

More from asmeerana605

More from asmeerana605 (20)

Can we use SQL in java.pptx.Join SQL Training in Chandigarh
Can we use SQL in java.pptx.Join SQL Training in ChandigarhCan we use SQL in java.pptx.Join SQL Training in Chandigarh
Can we use SQL in java.pptx.Join SQL Training in Chandigarh
 
Can I learn PHP course in 3 months..pptx
Can I learn PHP course in 3 months..pptxCan I learn PHP course in 3 months..pptx
Can I learn PHP course in 3 months..pptx
 
Best Certificate Courses In Chandigarh.pptx-presentation
Best Certificate Courses In Chandigarh.pptx-presentationBest Certificate Courses In Chandigarh.pptx-presentation
Best Certificate Courses In Chandigarh.pptx-presentation
 
Android course in chandigarh.pptx-presentation
Android course in chandigarh.pptx-presentationAndroid course in chandigarh.pptx-presentation
Android course in chandigarh.pptx-presentation
 
Content Writing Course in Chandigarh.pptx
Content Writing Course in Chandigarh.pptxContent Writing Course in Chandigarh.pptx
Content Writing Course in Chandigarh.pptx
 
Graphic designing course in chandigarh.pptx
Graphic designing course in chandigarh.pptxGraphic designing course in chandigarh.pptx
Graphic designing course in chandigarh.pptx
 
Certificate-Courses-In-Chandigarh.pptx-presentation
Certificate-Courses-In-Chandigarh.pptx-presentationCertificate-Courses-In-Chandigarh.pptx-presentation
Certificate-Courses-In-Chandigarh.pptx-presentation
 
Power BI course in Chandigarh.pptx-presentation
Power BI course in Chandigarh.pptx-presentationPower BI course in Chandigarh.pptx-presentation
Power BI course in Chandigarh.pptx-presentation
 
120 Hours Computer Course.pptx-presentation
120 Hours Computer Course.pptx-presentation120 Hours Computer Course.pptx-presentation
120 Hours Computer Course.pptx-presentation
 
Data Analytics Course in Chandigarh.pptx
Data Analytics Course in Chandigarh.pptxData Analytics Course in Chandigarh.pptx
Data Analytics Course in Chandigarh.pptx
 
Computer courses in Chandigarh Sector 34.pptx
Computer courses in Chandigarh Sector 34.pptxComputer courses in Chandigarh Sector 34.pptx
Computer courses in Chandigarh Sector 34.pptx
 
Marketing training in Chandigarh.pptx-presentation
Marketing training in Chandigarh.pptx-presentationMarketing training in Chandigarh.pptx-presentation
Marketing training in Chandigarh.pptx-presentation
 
Accounting Courses in chandigarh.pptx...
Accounting Courses in chandigarh.pptx...Accounting Courses in chandigarh.pptx...
Accounting Courses in chandigarh.pptx...
 
Cloud Computing Course in Chandigarh.pptx
Cloud Computing Course in Chandigarh.pptxCloud Computing Course in Chandigarh.pptx
Cloud Computing Course in Chandigarh.pptx
 
Artificial intelligence course in Chandigarh.pptx
Artificial intelligence course in Chandigarh.pptxArtificial intelligence course in Chandigarh.pptx
Artificial intelligence course in Chandigarh.pptx
 
Linux training in chandigarh.pptx Join Now
Linux training in chandigarh.pptx Join NowLinux training in chandigarh.pptx Join Now
Linux training in chandigarh.pptx Join Now
 
Cloud Computing Courses Online.pptx Join Now
Cloud Computing Courses Online.pptx Join NowCloud Computing Courses Online.pptx Join Now
Cloud Computing Courses Online.pptx Join Now
 
Web Designing training in Chandigarh.pptx
Web Designing training in Chandigarh.pptxWeb Designing training in Chandigarh.pptx
Web Designing training in Chandigarh.pptx
 
DevOps-training-in-chandigarh-Join-now--
DevOps-training-in-chandigarh-Join-now--DevOps-training-in-chandigarh-Join-now--
DevOps-training-in-chandigarh-Join-now--
 
SEO Training in Chandigarh Join Now.pptx
SEO Training in Chandigarh Join Now.pptxSEO Training in Chandigarh Join Now.pptx
SEO Training in Chandigarh Join Now.pptx
 

Recently uploaded

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
fonyou31
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Recently uploaded (20)

Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 

what are python basics.pptx.Join Python training in Chandigarh

  • 2. Introduction File handling is the process of reading and manipulating data from files. In Python, file handling is a fundamental skill for working with external data. Python provides a rich set of built-in functions to manage files. Use cases: storing program data, user configurations, logs, and exchanging data with other systems. We will delve into the essentials of file handling using Python. We'll cover concepts such as opening and closing files, reading data, writing content, and different file modes. By the end, you'll have a solid foundation for working with files effectively in your Python projects.
  • 3. Opening and Closing Files Use the open() function to open a file: file_object = open("filename", "mode") Common file modes: 'r' (read), 'w' (write), 'a' (append), 'x' (create) Create new files if they don't exist (with 'w' or 'x') Always close files with file_object.close() The open() function is the gateway to file operations in Python. It creates a file object that offers methods to interact with the file. The mode determines your level of access (read, write, etc). Closing files using close() releases system resources and prevents data corruption.
  • 4. Reading Data from Files The read() method returns the entire content as a string. The readline() method reads a single line at a time. The readlines() method reads all lines into a list of strings. Iterate over files using a for loop for line-by-line processing. Once a file is open in read mode, you have a variety of options to extract data. Choose the method best suited to your task—reading everything at once or working with lines individually. Looping through files allows you to process information systematically.
  • 5. Writing Data to Files Use the write() method to write a string to a file (mode 'w' or 'a'). 'w' mode overwrites existing content, 'a' mode appends to the end. Be careful about overwriting important files. writelines() can write a list of strings to a file. Files allow you to make your program's data persistent. The write() method is your primary tool for saving data to files. Manage how you modify existing files carefully, using either 'w' for overwrites or 'a' to add new content.
  • 6. File Modes 'r' (read): Open for reading (default). Raises an error if the file doesn't exist. 'w' (write): Open for writing, overwrites existing content, or creates a new file. 'x' (create): Creates a new file, fails if the file exists. 'a' (append): Open for writing, appends to the end, or creates if it doesn't exist. 'b' (binary): Used for binary files (images, videos) **'+' (update): ** For both reading and writing. These file modes give you granular control over how you interact with files. Choose the appropriate mode based on whether you need to read existing data, create new data, or update file contents.
  • 7. Working with CSV Files CSV (Comma-Separated Values) stores structured data in plain text. Use Python's csv module for handling CSV files. Import the module: import csv Use csv.reader() to read CSV data into rows. Use csv.writer() to write data into CSV format. CSV is a common format for storing tabular data. Python's csv module provides tools to easily read from and write data to CSV files, making it a great choice for interchanging data between systems.
  • 8. File Path Management Use the os module for file path operations. os.path.exists() checks if a file or directory exists. os.path.join() combines path components correctly. os.path.split() separates the filename from the path. Employ relative and absolute paths for file references. Organizing files and directories is crucial in larger projects. The os module helps navigate your file system—checking if files exist, constructing paths properly, and understanding file locations within your project structure.
  • 9. Error Handling Wrap file operations in try-except blocks. Common file-related exceptions: FileNotFoundError IOError PermissionError Provide meaningful error messages to the user. Ensure files are closed properly with a finally block Files are external resources; things can go wrong (missing files, permissions). Error handling with try-except makes your Python code robust and allows you to provide informative error messages if file operations fail.
  • 10. Conclusion Other Libraries: Explore libraries like pandas for advanced data manipulation. Binary Files: Learn about working with non-text data (images, audio, etc.) Context Managers: Use the with statement for more elegant file handling (with open(...) as file_object). File Handling Best Practices: Emphasize the importance of file handling in data-driven Python projects. These additional points hint at the broader world of file handling. Python offers a rich ecosystem of tools for data-related tasks, allowing you to work with various file formats. Wrap-up the presentation by reiterating the importance of file handling as a fundamental building block for many Python applications.
  • 11. What are Python basics? For Query Contact : 998874-1983