This document provides an overview of file handling in Python. It begins by outlining learning objectives related to understanding different file types, opening and closing files, and reading from and writing to files. It then discusses the need for data file handling to permanently store program data. Various file types are introduced, including text files, CSV files, and binary files. Methods for opening, reading from, writing to, and closing both text and binary files are described. The pickle module is explained for pickling and unpickling Python objects for storage in binary files. Finally, random access methods like tell() and seek() are briefly covered.
File handling is a key concept in programming that allows a program to create, open, read, write, and delete files on a storage device. It provides a way to store data permanently, even after the program execution ends, which is essential for managing data in applications.
Key Operations in File Handling
1. Creating Files: Files can be created in various modes (like text or binary) to store data. For example, in Python, the open() function with mode "w" (write mode) can create a new file.
2. Opening Files: Files can be opened in different modes:
• "r" (read): Opens an existing file for reading.
• "w" (write): Opens a file for writing, creates it if it doesn’t exist, and truncates it if it does.
• "a" (append): Opens a file for appending data at the end.
• "r+", "w+", and "a+": Variants that allow reading and writing together.
3. Reading Files: Content can be read using functions like read(), readline(), or readlines(). This helps to retrieve data from a file and process it within the program.
4. Writing to Files: The write() function adds content to a file. The mode chosen affects whether the content overwrites existing data or appends to it.
5. Closing Files: Closing files after reading or writing is essential as it frees system resources and ensures data is saved correctly.
6. File Deletion: Files can also be deleted if they are no longer needed, using commands like remove() in Python (from the os module).
Example Code in Python
Here’s a simple Python example showing basic file handling operations:
# Creating and writing to a file
with open("example.txt", "w") as file:
file.write("Hello, this is a sample text file.\n")
# Reading from the file
with open("example.txt", "r") as file:
content = file.read()
print(content)
Applications of File Handling
File handling is essential for many applications, such as:
• Data Storage: Persisting data, like saving user settings or logging information.
• File-Based Database: For lightweight applications, files can serve as a basic database.
• Data Processing: Reading data from files for analysis or processing.
• Configuration Files: Loading application configuration settings at runtime.
By understanding file handling, you can manage data effectively, making your programs more versatile and data-driven.
This document provides an overview of file handling in Python. It discusses different file types like text files, binary files, and CSV files. It explains how to open, read, write, close, and delete files using functions like open(), read(), write(), close(), and os.remove(). It also covers reading and writing specific parts of a file using readline(), readlines(), seek(), and tell(). The document demonstrates how to handle binary files using pickle for serialization and deserialization. Finally, it shows how the os module can be used for file operations and how the csv module facilitates reading and writing CSV files.
The document provides information about file handling in Python. It discusses the basic operations on files like opening, reading, writing and closing files. It explains text files and binary files, different file access modes, and methods to read and write data from/to files like readline(), readlines(), read(), write() and writelines(). It also covers random access methods like seek() and tell() as well as pickling and unpickling using the pickle module. Finally, it highlights the differences between text and binary files.
The document discusses data file handling in Python. It covers the basics of opening, reading from, and writing to both text and binary files.
The key points covered include: opening and closing files, different file access modes, reading methods like readline(), readlines(), and read(), writing methods like write() and writelines(), random access methods like seek() and tell(), pickling and unpickling using the pickle module, and the differences between text and binary files.
This document discusses files, modules, packages and exceptions in Python. It covers reading and writing to text files, opening and closing files, different file access modes, file positions, command line arguments, and common exceptions in Python like syntax errors and exceptions raised during execution. Key topics include using open(), read(), write(), close() functions to perform file operations, os and os.path modules for file and path operations, and sys.argv to access command line arguments in a Python program. Examples are provided for reading, writing, appending files and handling exceptions.
This document discusses file handling in Python. It explains that files are used to permanently store data as variables are volatile. There are three main types of files - text, binary, and CSV files. Text files store human-readable text while binary files contain arbitrary binary data. CSV files store tabular data with commas as the default delimiter. The document outlines the steps to process a file which include opening the file, performing operations, and closing the file. It specifically discusses binary files, noting they are encoded as byte streams and Python's pickle module is used to convert data to bytes for writing and back for reading. The pickle methods dump() and load() are used to write and read pickled data to and from binary files.
The document discusses file handling in Python. It covers opening and closing files, reading and writing to files, and different file access modes. It describes opening files using the open() function and closing files using the close() method. It explains how to read from files using methods like read(), readline(), and readlines(). It also covers writing to files using write(), writelines(), and seeking to specific positions using seek() and tell(). The document provides examples of reading, writing, and manipulating text files in Python.
Here are the answers to the quiz questions:
1. def read_file(file_name):
lines = []
with open(file_name, 'r') as f:
for line in f:
lines.append(line)
return lines
2. def input_list():
n = int(input("Enter number of elements : "))
list1 = []
for i in range(0, n):
ele = float(input())
list1.append(ele)
return list1
def output_list(list1):
for i in list1:
print(i)
3. def display_file(filename):
with open(filename
The document discusses file input/output in Python including:
1) Accessing keyboard input using input() and raw_input() functions;
2) Printing to the screen using the print() function;
3) Opening, reading, and writing to files using functions like open(), read(), write(), close();
4) Different file modes for reading, writing, appending text and binary files.
This document discusses data file handling in Python. It covers opening and closing files, reading and writing to files, binary files, relative and absolute paths, and standard I/O streams. The key points are that files allow storing persistent data, Python allows reading and writing files using functions like open(), read(), write(), and close(). Files can be text or binary, and different modes like read, write, and append are used for different file operations.
Microsoft power point chapter 5 file editedLinga Lgs
Files are used to store information permanently. There are two main types of files: text files and binary files. Text files store information in ASCII characters with each line separated by an end-of-line delimiter, while binary files store data in the same format as memory with no delimiters between lines. To work with files in Python, they must first be opened using the open() function, which returns a file object. This file object allows reading, writing, and manipulating file data using methods like read(), write(), readline(), and close().
FILE HANDLING in python to understand basic operations.ssuser00ad4e
The document discusses file handling in Python. It describes how to open, read from, write to, and close files. The key points are:
- Files can be opened in read, write, append modes using the open() function, which returns a file object.
- Reading file data uses functions like read(), readline(), and readlines(). Write uses write() and writelines().
- Files must be closed using the close() method on the file object after reading or writing to release system resources.
- Text files store data as characters while binary files store exact data types. Mode 'w' overwrites, 'a' appends without overwriting existing data.
This document provides an introduction to file handling in Python. It discusses different types of files like text files, binary files, and CSV files. It explains how to open, read, and write to files in various modes. It also covers pickling/unpickling for serialization and deserialization of Python objects to binary streams. Key file methods like open(), read(), readline(), readlines(), write(), and writelines() are described along with examples of working with CSV files using the csv module.
Textbook Solutions refer https://pythonxiisolutions.blogspot.com/
Practical's Solutions refer https://prippython12.blogspot.com/
Computer program works with files. This is because files help in storing information permanently. A file is a bunch of bytes stored on some secondary storage devices.
This document discusses file handling in Python. File handling allows Python programs to read from and write data to disk files for permanent storage. The open() function is used to open a file and return a file object, which has methods like read(), write(), close() to interact with the file. Files can be opened in different modes like read, write, append. The read() method reads from the file while write() writes to it. Files must be closed using close() after processing to flush buffers and close the file properly.
This document discusses file handling in Python. It begins by explaining that files allow permanent storage of data, unlike standard input/output which is volatile. It then covers opening files in different modes, reading and writing file contents using methods like read(), readline(), readlines(), seeking to different positions, and closing files. Examples are provided to illustrate reading temperature data from one file and writing converted values to another file. The document also discusses creating, deleting and renaming files and folders using OS module functions.
The document discusses file handling in Python. It begins by explaining the need for file handling such as storing data permanently and accessing it faster. It then defines what a file is and explains the different types of files - text files and binary files. It discusses the three main steps for file handling in Python - opening the file, processing the file by performing read/write operations, and closing the file. It also describes various file opening modes, methods for reading and writing text files, and modifying or appending content to text files.
How to Create Quotation Templates Sequence in Odoo 18 SalesCeline George
In this slide, we’ll discuss on how to create quotation templates sequence in Odoo 18 Sales. Odoo 18 Sales offers a variety of quotation templates that can be used to create different types of sales documents.
The document provides information about file handling in Python. It discusses the basic operations on files like opening, reading, writing and closing files. It explains text files and binary files, different file access modes, and methods to read and write data from/to files like readline(), readlines(), read(), write() and writelines(). It also covers random access methods like seek() and tell() as well as pickling and unpickling using the pickle module. Finally, it highlights the differences between text and binary files.
The document discusses data file handling in Python. It covers the basics of opening, reading from, and writing to both text and binary files.
The key points covered include: opening and closing files, different file access modes, reading methods like readline(), readlines(), and read(), writing methods like write() and writelines(), random access methods like seek() and tell(), pickling and unpickling using the pickle module, and the differences between text and binary files.
This document discusses files, modules, packages and exceptions in Python. It covers reading and writing to text files, opening and closing files, different file access modes, file positions, command line arguments, and common exceptions in Python like syntax errors and exceptions raised during execution. Key topics include using open(), read(), write(), close() functions to perform file operations, os and os.path modules for file and path operations, and sys.argv to access command line arguments in a Python program. Examples are provided for reading, writing, appending files and handling exceptions.
This document discusses file handling in Python. It explains that files are used to permanently store data as variables are volatile. There are three main types of files - text, binary, and CSV files. Text files store human-readable text while binary files contain arbitrary binary data. CSV files store tabular data with commas as the default delimiter. The document outlines the steps to process a file which include opening the file, performing operations, and closing the file. It specifically discusses binary files, noting they are encoded as byte streams and Python's pickle module is used to convert data to bytes for writing and back for reading. The pickle methods dump() and load() are used to write and read pickled data to and from binary files.
The document discusses file handling in Python. It covers opening and closing files, reading and writing to files, and different file access modes. It describes opening files using the open() function and closing files using the close() method. It explains how to read from files using methods like read(), readline(), and readlines(). It also covers writing to files using write(), writelines(), and seeking to specific positions using seek() and tell(). The document provides examples of reading, writing, and manipulating text files in Python.
Here are the answers to the quiz questions:
1. def read_file(file_name):
lines = []
with open(file_name, 'r') as f:
for line in f:
lines.append(line)
return lines
2. def input_list():
n = int(input("Enter number of elements : "))
list1 = []
for i in range(0, n):
ele = float(input())
list1.append(ele)
return list1
def output_list(list1):
for i in list1:
print(i)
3. def display_file(filename):
with open(filename
The document discusses file input/output in Python including:
1) Accessing keyboard input using input() and raw_input() functions;
2) Printing to the screen using the print() function;
3) Opening, reading, and writing to files using functions like open(), read(), write(), close();
4) Different file modes for reading, writing, appending text and binary files.
This document discusses data file handling in Python. It covers opening and closing files, reading and writing to files, binary files, relative and absolute paths, and standard I/O streams. The key points are that files allow storing persistent data, Python allows reading and writing files using functions like open(), read(), write(), and close(). Files can be text or binary, and different modes like read, write, and append are used for different file operations.
Microsoft power point chapter 5 file editedLinga Lgs
Files are used to store information permanently. There are two main types of files: text files and binary files. Text files store information in ASCII characters with each line separated by an end-of-line delimiter, while binary files store data in the same format as memory with no delimiters between lines. To work with files in Python, they must first be opened using the open() function, which returns a file object. This file object allows reading, writing, and manipulating file data using methods like read(), write(), readline(), and close().
FILE HANDLING in python to understand basic operations.ssuser00ad4e
The document discusses file handling in Python. It describes how to open, read from, write to, and close files. The key points are:
- Files can be opened in read, write, append modes using the open() function, which returns a file object.
- Reading file data uses functions like read(), readline(), and readlines(). Write uses write() and writelines().
- Files must be closed using the close() method on the file object after reading or writing to release system resources.
- Text files store data as characters while binary files store exact data types. Mode 'w' overwrites, 'a' appends without overwriting existing data.
This document provides an introduction to file handling in Python. It discusses different types of files like text files, binary files, and CSV files. It explains how to open, read, and write to files in various modes. It also covers pickling/unpickling for serialization and deserialization of Python objects to binary streams. Key file methods like open(), read(), readline(), readlines(), write(), and writelines() are described along with examples of working with CSV files using the csv module.
Textbook Solutions refer https://pythonxiisolutions.blogspot.com/
Practical's Solutions refer https://prippython12.blogspot.com/
Computer program works with files. This is because files help in storing information permanently. A file is a bunch of bytes stored on some secondary storage devices.
This document discusses file handling in Python. File handling allows Python programs to read from and write data to disk files for permanent storage. The open() function is used to open a file and return a file object, which has methods like read(), write(), close() to interact with the file. Files can be opened in different modes like read, write, append. The read() method reads from the file while write() writes to it. Files must be closed using close() after processing to flush buffers and close the file properly.
This document discusses file handling in Python. It begins by explaining that files allow permanent storage of data, unlike standard input/output which is volatile. It then covers opening files in different modes, reading and writing file contents using methods like read(), readline(), readlines(), seeking to different positions, and closing files. Examples are provided to illustrate reading temperature data from one file and writing converted values to another file. The document also discusses creating, deleting and renaming files and folders using OS module functions.
The document discusses file handling in Python. It begins by explaining the need for file handling such as storing data permanently and accessing it faster. It then defines what a file is and explains the different types of files - text files and binary files. It discusses the three main steps for file handling in Python - opening the file, processing the file by performing read/write operations, and closing the file. It also describes various file opening modes, methods for reading and writing text files, and modifying or appending content to text files.
How to Create Quotation Templates Sequence in Odoo 18 SalesCeline George
In this slide, we’ll discuss on how to create quotation templates sequence in Odoo 18 Sales. Odoo 18 Sales offers a variety of quotation templates that can be used to create different types of sales documents.
Artificial intelligence Presented by JM.jmansha170
AI (Artificial Intelligence) :
"AI is the ability of machines to mimic human intelligence, such as learning, decision-making, and problem-solving."
Important Points about AI:
1. Learning – AI can learn from data (Machine Learning).
2. Automation – It helps automate repetitive tasks.
3. Decision Making – AI can analyze and make decisions faster than humans.
4. Natural Language Processing (NLP) – AI can understand and generate human language.
5. Vision & Recognition – AI can recognize images, faces, and patterns.
6. Used In – Healthcare, finance, robotics, education, and more.
Owner By:
Name : Junaid Mansha
Work : Web Developer and Graphics Designer
Contact us : +92 322 2291672
Email : [email protected]
Adam Grant: Transforming Work Culture Through Organizational PsychologyPrachi Shah
This presentation explores the groundbreaking work of Adam Grant, renowned organizational psychologist and bestselling author. It highlights his key theories on giving, motivation, leadership, and workplace dynamics that have revolutionized how organizations think about productivity, collaboration, and employee well-being. Ideal for students, HR professionals, and leadership enthusiasts, this deck includes insights from his major works like Give and Take, Originals, and Think Again, along with interactive elements for enhanced engagement.
This presentation has been made keeping in mind the students of undergraduate and postgraduate level. To keep the facts in a natural form and to display the material in more detail, the help of various books, websites and online medium has been taken. Whatever medium the material or facts have been taken from, an attempt has been made by the presenter to give their reference at the end.
In the seventh century, the rule of Sindh state was in the hands of Rai dynasty. We know the names of five kings of this dynasty- Rai Divji, Rai Singhras, Rai Sahasi, Rai Sihras II and Rai Sahasi II. During the time of Rai Sihras II, Nimruz of Persia attacked Sindh and killed him. After the return of the Persians, Rai Sahasi II became the king. After killing him, one of his Brahmin ministers named Chach took over the throne. He married the widow of Rai Sahasi and became the ruler of entire Sindh by suppressing the rebellions of the governors.
Parenting Teens: Supporting Trust, resilience and independencePooky Knightsmith
For more information about my speaking and training work, visit: https://www.pookyknightsmith.com/speaking/
SESSION OVERVIEW:
Parenting Teens: Supporting Trust, Resilience & Independence
The teenage years bring new challenges—for teens and for you. In this practical session, we’ll explore how to support your teen through emotional ups and downs, growing independence, and the pressures of school and social life.
You’ll gain insights into the teenage brain and why boundary-pushing is part of healthy development, along with tools to keep communication open, build trust, and support emotional resilience. Expect honest ideas, relatable examples, and space to connect with other parents.
By the end of this session, you will:
• Understand how teenage brain development affects behaviour and emotions
• Learn ways to keep communication open and supportive
• Explore tools to help your teen manage stress and bounce back from setbacks
• Reflect on how to encourage independence while staying connected
• Discover simple strategies to support emotional wellbeing
• Share experiences and ideas with other parents
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...EduSkills OECD
Deborah Nusche, Senior Analyst, OECD presents at the OECD webinar 'Trends Spotting: Strategic foresight for tomorrow’s education systems' on 5 June 2025. You can check out the webinar on the website https://oecdedutoday.com/webinars/ Other speakers included: Deborah Nusche, Senior Analyst, OECD
Sophie Howe, Future Governance Adviser at the School of International Futures, first Future Generations Commissioner for Wales (2016-2023)
Davina Marie, Interdisciplinary Lead, Queens College London
Thomas Jørgensen, Director for Policy Coordination and Foresight at European University Association
Unit- 4 Biostatistics & Research Methodology.pdfKRUTIKA CHANNE
Blocking and confounding (when a third variable, or confounder, influences both the exposure and the outcome) system for Two-level factorials (a type of experimental design where each factor (independent variable) is investigated at only two levels, typically denoted as "high" and "low" or "+1" and "-1")
Regression modeling (statistical model that estimates the relationship between one dependent variable and one or more independent variables using a line): Hypothesis testing in Simple and Multiple regression models
Introduction to Practical components of Industrial and Clinical Trials Problems: Statistical Analysis Using Excel, SPSS, MINITAB®️, DESIGN OF EXPERIMENTS, R - Online Statistical Software to Industrial and Clinical trial approach
This presentation was provided by Jennifer Gibson of Dryad, during the first session of our 2025 NISO training series "Secrets to Changing Behavior in Scholarly Communications." Session One was held June 5, 2025.
How to Configure Vendor Management in Lunch App of Odoo 18Celine George
The Vendor management in the Lunch app of Odoo 18 is the central hub for managing all aspects of the restaurants or caterers that provide food for your employees.
This presentation was provided by Nicole 'Nici" Pfeiffer of the Center for Open Science (COS), during the first session of our 2025 NISO training series "Secrets to Changing Behavior in Scholarly Communications." Session One was held June 5, 2025.
How to Manage & Create a New Department in Odoo 18 EmployeeCeline George
In Odoo 18's Employee module, organizing your workforce into departments enhances management and reporting efficiency. Departments are a crucial organizational unit within the Employee module.
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecdrazelitouali
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Pests of Rice: Damage, Identification, Life history, and Management.pptxArshad Shaikh
Rice pests can significantly impact crop yield and quality. Major pests include the brown plant hopper (Nilaparvata lugens), which transmits viruses like rice ragged stunt and grassy stunt; the yellow stem borer (Scirpophaga incertulas), whose larvae bore into stems causing deadhearts and whiteheads; and leaf folders (Cnaphalocrocis medinalis), which feed on leaves reducing photosynthetic area. Other pests include rice weevils (Sitophilus oryzae) and gall midges (Orseolia oryzae). Effective management strategies are crucial to minimize losses.
How to Manage Upselling of Subscriptions in Odoo 18Celine George
Subscriptions in Odoo 18 are designed to auto-renew indefinitely, ensuring continuous service for customers. However, businesses often need flexibility to adjust pricing or quantities based on evolving customer needs.
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxArshad Shaikh
Diptera, commonly known as flies, is a large and diverse order of insects that includes mosquitoes, midges, gnats, and horseflies. Characterized by a single pair of wings (hindwings are modified into balancing organs called halteres), Diptera are found in almost every environment and play important roles in ecosystems as pollinators, decomposers, and food sources. Some species, however, are significant pests and disease vectors, transmitting diseases like malaria, dengue, and Zika virus.
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxPoojaSen20
Ad
FILE HANDLING IN PYTHON Presentation Computer Science
1. Chapter - 5
File Handling in PYTHON
File:
File is the basic unit of storage which used to store the data permanently.
A file itself is a bunch of bytes stored on some storage device like hard disk or thumb
drive or any secondary storage device
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.
In programming, Sometimes, it is not enough to only display the data on the console.
Those data are to be retrieved later on, then the concept of file handling comes.
It is impossible to recover the programmatically generated data again and again. However,
if we need to do so, we may store it onto the file system which is not volatile and can be
accessed every time. Here, comes the need of file handling in Python.
2. Data file:
The data files are the files that store data pertaining to a specific application,
for later user. The data file can be stored in two ways:
TEXT FILE
BINARY FILE
Text File:
A text file stores information in the form of a stream of ASCII or Unicode
character. In text file, each line of text is terminated, with a special character
known as EOL (End of Line) character. In text files, some internal translation
take place when this EOL character is read or written. In python, by default,
this EOL character is the newline character (‘n’) or carriage-return, new line
character(‘rn’)
3. Type of text file:
i) Regular Text fie: These are the text files which store the text in the same form as typed. Here the new line character(‘n’)
ends the line and the file extension is .txt.
ii) Delimited text file: In these text files, a specific character is sored to separate the values, i.e., after each value, e.g., a
TAB or a COMMA after every value.
When a tab is used to separate the values stored, these are called TSV files( Tab Separated Values).These files can
take the extension as .txt or .csv
When the comma is used to separate the values stored, these are called as CSV files(Comma Separated
Values). These files take extension as .csv
Binary File:
A binary file stores the information in the form of stream of bytes. A binary file contains information in the sam format in
which the information is held in memory, i.e., the file content that is returned a raw format. In binary file, there is no
delimiter character for a line and also no translation occur.
The CSV format is a popular import and export format for spreadsheet and databases.
The text files can be opened in any text editor and are in human readable form while binary files are not in
human readable form.
The .exe files, mp3 file, image files are some of the examples of binary files. we can’t read a binary file using a
text editor.
4. Text File Binary File
Its Bits represent character. Its Bits represent a custom data.
Less prone to get corrupt as change
reflects as soon as made and can be
undone.
Can easily get corrupted, corrupt on even
single bit change
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.
There is a delimiting character There is no delimiting character
DIFFERENCE BETWEEN TEXT FILE AND BINARY FILE
5. Opening and Closing Files:
File handling in Python enables us to create, update, read, and delete the
data stored on the file system through our python program. The following
operations can be performed on a file.
In Python, File Handling consists of following three steps:
Open the file.
Process file i.e perform read or write operation.
Close the file.
To perform file operation ,it must be opened first, then after reading,
writing, editing operation can be performed. 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.
6. Text file Binary file CSV file
READ()
READLINE()
READLINES()
WRITE()
WRITELINES()
DUMP()
LOAD()
CSV.WRITER()
WRITEROW()
WRITEROWS()
CSV.READER()
COMMON FOR ALL THREE TYPES OF FILES
FILE HANDLING FUNCTIONS:
7. 1.The Open( ) Method:
Before any reading or writing operation of any file, it must be opened first. Python provide built in function
open() for it. On calling of this function ,creates file object for file operations.
Syntax
file object = open( file_name, access_mode )
File object: It is an Identifier which acts as an interface between file and the user. It can be called as file
handle.
file_name = name of the file ,enclosed in double quotes.
access_mode= Determines the what kind of operations can be performed with file,like read,write etc.
For example : file1= open(“sample.txt”)
file1= open(“sample.txt”, ”r”)
file mode is optional, default file mode is read only(“r”)
8. Text file Binary file Description Explanation
‘r’ ‘rb’ Read only File must exist already, otherwise raises I/O error
‘w’ ‘wb’ Write only If the file does not exist, file is created
If the file exists, will truncate existing data and
over-write in the file.
‘a’ ‘ab’ Append File is in write only mode.
If the file exists, the data in the file is retained and
new data being appended to the end.
If the file does not exit, python will create a new
file.
FILE ACCESS MODE / FILE OPENING MODE:
The file access mode describes that how the file will be used in the program i.e to read data
from the file or to write data into the file or add the data into the file.
9. Text file Binary file Description Explanation
‘r+’ ‘ r+b’ or
‘rb+’
Read and
write
File must exist otherwise error is raised.
Both reading and writing operations can take place.
‘w+’ ‘w+b’ or
‘wb+’
Write and read File is created if does not exist.
If file exists, file is truncated.
Both reading and writing operations can take place.
‘a+’ ‘a+b’ or
‘ab+’
Write and read File is created if does not exist.
If file exists, file’s existing data is retained, new data
is appended.
Both reading and writing operations can take place.
10. 2. The close() Method:
close(): Used to close an open file. After using this method, an opened file will be closed.
F1 = open(“sample.txt”, “w”)
-----
-----
F1.close()
3. The write() Method
It writes a string the text file.
Syntax:
File-handle. Write( string variable)
Example: s1=“Venkat International public school n“
s2=“Affiliated to CBSE n ”
F1.write(s1)
F1.write(s2)
11. 4. The writelines( ) Method:
It is used to write all the strings in the list as lines to the text file referenced by the file handle.
Systax:
File-Handle.writelines(list)
Example:
f1= open(“sample.txt”, “w”)
l= [ ]
s1=“Venkat International public school “
s2=“nAffiliated to CBSE”
l.append(s1)
l.append(s2)
f1.writelines(l)
Sample.txt
Venkat International Public School
Affiliated to CBSE
12. 5. The read() Method
It reads the entire file and returns it contents in the form of a string. Reads at most size bytes or less if end of
file occurs. If size not mentioned then read the entire file contents.
Syntax:
File_Handle.read( [ size] )
- size is optional
Example:
f = open(“sample.txt” , ”r”)
1. s= f. read( )
print(s)
o/p: Venkat International Public School
Affiliated to CBSE”
2. s= f.read(6)
print(s)
s=f.read(14)
print(s)
o/p: Venkat
International
13. 6. The readline([size]) method:
It reads a line of input, if n is specified read at most n byte( n characters ) from the text file. It returns the
data in the form string ending with newline (‘n’) character or returns a blank string if no more bytes are left
for reading in the file.
Syntax:
FileHandle.readline( )
Example:
1. f = open(“sample.txt” , ”r”)
s=f.readline()
print(s)
s= f.readline()
print(s)
o/p:
Venkat International Public School
Affiliated to CBSE
2. s=f.readline(20)
print(s)
o/p: Venkat International
14. 7. The readlines( ) method:
It reads all lines from the text file and returns them in a list.
Syntax:
FileHandle.readlines( )
Example:
1. f = open(“sample.txt” , ”r”)
s=f.readlines()
print(s)
o/p:
[“Venkat International Public Schooln”, “Affiliated to CBSEn” ]
2. L =f.readlines()
for i in L:
print(i)
o/p:
Venkat International Public School
Affiliated to CBSE
15. Operations on Binary file:
Pickle Module:
dump()- It is used to store an object( list or dictionary or tuple…) into a binary
file.
Syntax:
pickle.dump( objectname, file_handle)
Example:
f1=open(“student.dat”, ”wb” )
Rec = [1001,”Raj kumar”, 98.5]
pickle.dump(Rec,f1)
16. Load( ) - It is used to read an object( list or dictionary or tuple…) from a binary
file.
Syntax:
objectname = pickle.load( file_handle)
Example:
f1=open(“student.dat”, ”rb”)
Rec= pickle.load(f1)
Rec[0]= 1001
Rec[1]=Raj kumar
Rec[2]=98.5
18. import pickle
def Create( ):
f1= open("employee.dat","wb")
while True:
empid= int(input("Enter the employee id : "))
ename=input("Enter the employee name ")
salary=int(input("Enter the Salary "))
Rec= [empid, ename, salary ]
pickle.dump(Rec, f1 )
ch=input("Do you want to create another record y/ n ")
if ch=="n" or ch=="N":
break
f1.close()
21. CSV FILES
The separator character of CSV files is called a delimiter. Default and most
popular delimiter is comma. Other popular delimiters include the tab (t),
colon(:), pipe(|) and semi-colon(;) characters.
The csv module of python provides functionality to read and write tabular data
in csv format. It provides two specific types of objects- the reader object and
writer objects- to read and write into CSV files. The csv module’s reader and
writer objects read and write delimited sequences as records in a CSV files.
Opening a CSV file:
Syntax:
File-handle = open(“filename.csv”, “mode” [, newline=’n’])
22. csv.writer( )
csv files are delimited flat files and before writing onto them, the data must be in
csv-writable-delimited form, it is important to convert the received user data into the form
appropriate for the csv files.
This task is performed by the writer object.
Systax:
Writer-object-name= csv.writer(file-handle[, delimiter character] )
example:
wr= csv.writer(f1, delimiter=‘,’)
23. csv.wrirerow( ): it writes one row of information onto the csv-file.
Syntax:
Writer-object.writerow(sequence )
csv.wrirerows( ): it writes multiple rows of information onto the csv-file.
Syntax:
Writer-object.writerows(sequence )
24. csv.reader():
The csv reader object loads data from the csv file, parses it, ie removes
the delimiters and returns the data in the form of a python iterable
wherefrom we can fetch one row of data at a time.
Syntax:
List= cse.reader(filehandle [, delimiter=‘ delimiter character])
29. Random Access on file:
tell( ) - functions returns the current position of file pointer
in the file.
Syntax:
File-object.tell()
Initial position of file pointer is zero.
30. seek() -function changes the position of file pointer to the
specified place in the file.
Systax:
File-object.seek(offset ,[ mode])
Offset- specify the no. of bytes
Mode – 0 from beginning of the file
1 from the current position
2 from the end of the file.
31. Sample.txt
The csv module of python provides functionality to read
and write tabular data in csv format. It provides two
specific types of objects- the reader object and writer
objects- to read and write into CSV files. The csv
module’s reader and writer objects read and write
delimited sequences as records in a CSV files.
F1= open(“sample.txt”, “r”)