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.
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 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.
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. 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 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.
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.
The document discusses file handling in Python. It explains that a file is used to permanently store data in non-volatile memory. It describes opening, reading, writing, and closing files. It discusses opening files in different modes like read, write, append. It also explains attributes of file objects like name, closed, and mode. The document also covers reading and writing text and binary files, pickle module for serialization, and working with CSV files and the os.path module.
The document discusses Python's built-in functions and methods for reading, writing, and manipulating files and directories. It explains how to open and close files, read and write file contents, check file positions, rename and delete files, create and remove directories, and get the current working directory using functions like open(), close(), read(), write(), tell(), seek(), os.rename(), os.remove(), os.mkdir(), os.chdir(), and os.getcwd(). It also covers the different modes for opening files and lists attributes of file objects.
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.
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
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 Python's built-in functions and methods for performing input/output operations (I/O) and manipulating files and directories. It covers printing to the screen, reading keyboard input, opening and closing files, reading and writing files, file positions, renaming and deleting files, and creating, removing, and changing directories.
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.
The document discusses files and file handling in Python. It describes the different types of files (text and binary), how to open and close files, the various modes for opening files, and methods for reading and writing data to files. It also covers built-in file attributes, standard files, and exception handling related to file operations.
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.
File Handling Btech computer science and engineering pptpinuadarsh04
Data is very important. Every organization depends on its data for continuing its business operations. If the data is lost, the organization has to be closed. To store data in a computer, we need files. For example, we can store employee data like employee number, name and salary in a file in the computer and later use it whenever we want.
Similarly, we can store student data like student roll number, name and marks in the computer. In computers’ view, a file is nothing but collection of data that is available to a program. Once we store data in a computer file, we can retrieve it and use it depending on our requirements.
This is the reason computers are primarily created for handling data, especially for storing and retrieving data. In later days, programs are developed to process the data that is stored in the computer.
Files in Python represent sequences of bytes stored on disk for permanent storage. They can be opened in different modes like read, write, append etc using the open() function, which returns a file object. Common file operations include writing, reading, seeking to specific locations, and closing the file. The with statement is recommended for opening and closing files to ensure they are properly closed even if an exception occurs.
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.
*Order Hemiptera:*
Hemiptera, commonly known as true bugs, is a large and diverse order of insects that includes cicadas, aphids, leafhoppers, and shield bugs. Characterized by their piercing-sucking mouthparts, Hemiptera feed on plant sap, other insects, or small animals. Many species are significant pests, while others are beneficial predators.
*Order Neuroptera:*
Neuroptera, also known as net-winged insects, is an order of insects that includes lacewings, antlions, and owlflies. Characterized by their delicate, net-like wing venation and large, often prominent eyes, Neuroptera are predators that feed on other insects, playing an important role in biological control. Many species have aquatic larvae, adding to their ecological diversity.
More Related Content
Similar to file handling in python using exception statement (20)
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. 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 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.
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.
The document discusses file handling in Python. It explains that a file is used to permanently store data in non-volatile memory. It describes opening, reading, writing, and closing files. It discusses opening files in different modes like read, write, append. It also explains attributes of file objects like name, closed, and mode. The document also covers reading and writing text and binary files, pickle module for serialization, and working with CSV files and the os.path module.
The document discusses Python's built-in functions and methods for reading, writing, and manipulating files and directories. It explains how to open and close files, read and write file contents, check file positions, rename and delete files, create and remove directories, and get the current working directory using functions like open(), close(), read(), write(), tell(), seek(), os.rename(), os.remove(), os.mkdir(), os.chdir(), and os.getcwd(). It also covers the different modes for opening files and lists attributes of file objects.
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.
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
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 Python's built-in functions and methods for performing input/output operations (I/O) and manipulating files and directories. It covers printing to the screen, reading keyboard input, opening and closing files, reading and writing files, file positions, renaming and deleting files, and creating, removing, and changing directories.
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.
The document discusses files and file handling in Python. It describes the different types of files (text and binary), how to open and close files, the various modes for opening files, and methods for reading and writing data to files. It also covers built-in file attributes, standard files, and exception handling related to file operations.
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.
File Handling Btech computer science and engineering pptpinuadarsh04
Data is very important. Every organization depends on its data for continuing its business operations. If the data is lost, the organization has to be closed. To store data in a computer, we need files. For example, we can store employee data like employee number, name and salary in a file in the computer and later use it whenever we want.
Similarly, we can store student data like student roll number, name and marks in the computer. In computers’ view, a file is nothing but collection of data that is available to a program. Once we store data in a computer file, we can retrieve it and use it depending on our requirements.
This is the reason computers are primarily created for handling data, especially for storing and retrieving data. In later days, programs are developed to process the data that is stored in the computer.
Files in Python represent sequences of bytes stored on disk for permanent storage. They can be opened in different modes like read, write, append etc using the open() function, which returns a file object. Common file operations include writing, reading, seeking to specific locations, and closing the file. The with statement is recommended for opening and closing files to ensure they are properly closed even if an exception occurs.
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.
*Order Hemiptera:*
Hemiptera, commonly known as true bugs, is a large and diverse order of insects that includes cicadas, aphids, leafhoppers, and shield bugs. Characterized by their piercing-sucking mouthparts, Hemiptera feed on plant sap, other insects, or small animals. Many species are significant pests, while others are beneficial predators.
*Order Neuroptera:*
Neuroptera, also known as net-winged insects, is an order of insects that includes lacewings, antlions, and owlflies. Characterized by their delicate, net-like wing venation and large, often prominent eyes, Neuroptera are predators that feed on other insects, playing an important role in biological control. Many species have aquatic larvae, adding to their ecological diversity.
HOW YOU DOIN'?
Cool, cool, cool...
Because that's what she said after THE QUIZ CLUB OF PSGCAS' TV SHOW quiz.
Grab your popcorn and be seated.
QM: THARUN S A
BCom Accounting and Finance (2023-26)
THE QUIZ CLUB OF PSGCAS.
Ray Dalio How Countries go Broke the Big CycleDadang Solihin
A complete and practical understanding of the Big Debt Cycle. A much more practical understanding of how supply and demand really work compared to the conventional economic thinking. A complete and practical understanding of the Overall Big Cycle, which is driven by the Big Debt Cycle and the other major cycles, including the big political cycle within countries that changes political orders and the big geopolitical cycle that changes world orders.
A short update and next week. I am writing both Session 9 and Orientation S1.
As a Guest Student,
You are now upgraded to Grad Level.
See Uploads for “Student Checkin” & “S8”. Thx.
Thank you for attending our workshops.
If you are new, do welcome.
Grad Students: I am planning a Reiki-Yoga Master Course (As a package). I’m Fusing both together.
This will include the foundation of each practice. Our Free Workshops can be used with any Reiki Yoga training package. Traditional Reiki does host rules and ethics. Its silent and within the JP Culture/Area/Training/Word of Mouth. It allows remote healing but there’s limits As practitioners and masters. We are not allowed to share certain secrets/tools. Some content is designed only for “Masters”. Some yoga are similar like the Kriya Yoga-Church (Vowed Lessons). We will review both Reiki and Yoga (Master tools) in the Course upcoming.
Session Practice, For Reference:
Before starting a session, Make sure to check your environment. Nothing stressful. Later, You can decorate a space as well.
Check the comfort level, any needed resources (Yoga/Reiki/Spa Props), or Meditation Asst?
Props can be oils, sage, incense, candles, crystals, pillows, blankets, yoga mat, any theme applies.
Select your comfort Pose. This can be standing, sitting, laying down, or a combination.
Monitor your breath. You can add exercises.
Add any mantras or affirmations. This does aid mind and spirit. It helps you to focus.
Also you can set intentions using a candle.
The Yoga-key is balancing mind, body, and spirit.
Finally, The Duration can be long or short.
Its a good session base for any style.
Next Week’s Focus:
A continuation of Intuition Development. We will review the Chakra System - Our temple. A misguided, misused situation lol. This will also serve Attunement later.
For Sponsor,
General updates,
& Donations:
Please visit:
https://ldmchapels.weebly.com
How to Manage Maintenance Request in Odoo 18Celine George
Efficient maintenance management is crucial for keeping equipment and work centers running smoothly in any business. Odoo 18 provides a Maintenance module that helps track, schedule, and manage maintenance requests efficiently.
THE QUIZ CLUB OF PSGCAS BRINGS T0 YOU A FUN-FILLED, SEAT EDGE BUSINESS QUIZ
DIVE INTO THE PRELIMS OF BIZCOM 2024
QM: GOWTHAM S
BCom (2022-25)
THE QUIZ CLUB OF PSGCAS
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.
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
Completed Sunday 6/8. For Weekend 6/14 & 15th. (Fathers Day Weekend US.) These workshops are also timeless for future students TY. No admissions needed.
A 9th FREE WORKSHOP
Reiki - Yoga
“Intuition-II, The Chakras”
Your Attendance is valued.
We hit over 5k views for Spring Workshops and Updates-TY.
Thank you for attending our workshops.
If you are new, do welcome.
Grad Students: I am planning a Reiki-Yoga Master Course (As a package). I’m Fusing both together.
This will include the foundation of each practice. Our Free Workshops can be used with any Reiki Yoga training package. Traditional Reiki does host rules and ethics. Its silent and within the JP Culture/Area/Training/Word of Mouth. It allows remote healing but there’s limits As practitioners and masters, we are not allowed to share certain secrets/tools. Some content is designed only for “Masters”. Some yoga are similar like the Kriya Yoga-Church (Vowed Lessons). We will review both Reiki and Yoga (Master tools) in the Course upcoming.
S9/This Week’s Focus:
* A continuation of Intuition-2 Development. We will review the Chakra System - Our temple. A misguided, misused situation lol. This will also serve Attunement later.
Thx for tuning in. Your time investment is valued. I do select topics related to our timeline and community. For those seeking upgrades or Reiki Levels. Stay tuned for our June packages. It’s for self employed/Practitioners/Coaches…
Review & Topics:
* Reiki Is Japanese Energy Healing used Globally.
* Yoga is over 5k years old from India. It hosts many styles, teacher versions, and it’s Mainstream now vs decades ago.
* Anything of the Holistic, Wellness Department can be fused together. My origins are Alternative, Complementary Medicine. In short, I call this ND. I am also a metaphysician. I learnt during the 90s New Age Era. I forget we just hit another wavy. It’s GenZ word of Mouth, their New Age Era. WHOA, History Repeats lol. We are fusing together.
* So, most of you have experienced your Spiritual Awakening. However; The journey wont be perfect. There will be some roller coaster events. The perks are: We are in a faster Spiritual Zone than the 90s. There’s more support and information available.
(See Presentation for all sections, THX AGAIN.)
Exploring Ocean Floor Features for Middle SchoolMarie
This 16 slide science reader is all about ocean floor features. It was made to use with middle school students.
You can download the PDF at thehomeschooldaily.com
Thanks! Marie
Strengthened Senior High School - Landas Tool Kit.pptxSteffMusniQuiballo
Landas Tool Kit is a very helpful guide in guiding the Senior High School students on their SHS academic journey. It will pave the way on what curriculum exits will they choose and fit in.
Different pricelists for different shops in odoo Point of Sale in Odoo 17Celine George
Price lists are a useful tool for managing the costs of your goods and services. This can assist you in working with other businesses effectively and maximizing your revenues. Additionally, you can provide your customers discounts by using price lists.
Different pricelists for different shops in odoo Point of Sale in Odoo 17Celine George
Ad
file handling in python using exception statement
2. A file (i.e. data file) is a named place on the disk
where a sequence of related data is stored. In
python files are simply stream of data, so the
structure of data is not stored in the file, along
with data.
Basic operations performed on a data file are:
Naming a file
Opening a file
Reading data from the file
Writing data in the file
Closing a file
3. Using these basic operations, we can process file
in many ways, such as
Creating a file
Traversing a file for displaying the data on screen
Appending data in file
Inserting data in file
Deleting data from file
Create a copy of file
Updating data in the file, etc.
Python allow us to create and manage two types
of file
Text
Binary
4. A text file is usually considered as sequence
of lines. Line is a sequence of characters
(ASCII), stored on permanent storage media.
Although default character coding in python
is ASCII but using constant u with string,
supports Unicode as well.
Each line is terminated by a special character,
known as End of Line (EOL). From strings we
know that n is newline character. So at the
lowest level, text file will be collection of
bytes. Text files are stored in human readable
form and they can also be created using any
text editor
5. A binary file contains arbitrary binary data i.e.
numbers stored in the file, can be used for
numerical operation(s). So when we work on
binary file, we have to interpret the raw bit
pattern(s) read from the file into correct type of
data in our program.
It is perfectly possible to interpret a stream of
bytes originally written as string, as numeric
value. But we know that will be incorrect
interpretation of data and we are not going to get
desired output after the file processing activity.
So in the case of binary file it is extremely
important that we interpret the correct data type
while reading the file. Python provides special
module(s) for encoding and decoding of data for
binary file.
6. To handle data files in python, we need to have
a file object. Object can be created by using
open() function or file() function. To work on
file, first thing we do is open it. This is done by
using built in function open().
Using this function a file object is created
which is then used for accessing various
methods and functions available for file
manipulation.
Syntax of open() function is
file_object = open(filename [, access_mode]
[,buffering])
7. open() requires three arguments to
work, first one ( filename ) is the
name of the file . The name can
include the description of path.
The second parameter (access_mode)
describes how file will be used
throughout the program. This is an
optional parameter and the default
access_mode is reading.
8. The third parameter (buffering) is for specifying
how much is read from the file in one read. The
function will return an object of file type using
which we will manipulate the file, in our program.
When we work with file(s), a buffer (area in
memory where data is temporarily stored before
being written to file), is automatically associated
with file when we open the file. While writing the
content in the file, first it goes to buffer and once
the buffer is full, data is written to the file. Also
when file is closed, any unsaved data is
transferred to file. flush() function is used to
force transfer of data from buffer to file.
9. File access modes
r will open the text file for reading only and rb will do
the same for binary format file.
w will open a text file for writing only and wb for
binary format file.
r+ will open a text file and rb+ will open a binary file,
for both reading and writing purpose. The file pointer
is placed at the beginning of the file when it is
opened using r+ / rb+ mode.
w+ opens a file in text format and wb+ in binary
format, for both writing and reading. File pointer will
be placed at the beginning for writing into it, so an
existing file will be overwritten. A new file can also be
created using this mode.
a+ opens a text file and ab+ opens a binary file, for
both appending and reading. File pointer is placed at
the end of the file, in an already existing file. Using
this mode a non existing file may be created.
10. fileobject. close() will be used to close the file
object, once we have finished working on it.
readline() will return a line read, as a string
from the file
fileobject.readline()
Since the method returns a string it's usage
will be
>>>x = file.readline()
or
>>>print file.readline()
11. readlines()can be used to read the entire
content of the file. You need to be careful
while using it w.r.t. size of memory required
before using the function. The method will
return a list of strings, each separated by
n.
An example of reading entire data of file in
list is:
It's syntax is:
fileobject.readlines()
as it returns a list, which can then be used for
manipulation.
12. read() can be used to read specific size string
from file. This function also returns a string read
from the file.
At the end of the file, again an empty string will
be returned.
Syntax of read() function is
fileobject.read([size])
Here size specifies the number of bytes to be
read from the file.
lines = []
content = file.read() # since no size is given,
entire file will be read
lines = content.splitlines()
print lines
will give you a list of strings:
['hello world.', 'this is my first file handling
program.', 'I am using python language.']
13. For sending data in file, i.e. to create / write
in the file, write() and writelines() methods
can be used.
write() method takes a string ( as parameter )
and writes it in the file. For storing data with
end of line character, you will have to add n
character to end of the string.
Notice addition of n in the end of every
sentence while talking of data.txt. As
argument to the function has to be string, for
storing numeric value, we have to convert it
to string.
14. Its syntax is
fileobject.write(string)
Example
>>>f = open('test1.txt','w')
>>>f.write("hello worldn")
>>>f.close()
For numeric data value conversion to string is
required.
Example
>>>x = 52
>>>file.write(str(x))
15. For writing a string at a time, we use write()
method, it can't be used for writing a list, tuple
etc. into a file.
Sequence data type can be written using
writelines() method in the file. It's not that, we
can't write a string
using writelines() method.
It's syntax is:
fileobject.writelines(seq)
So, whenever we have to write a sequence of
string / data type, we will use writelines(), instead
of write().
f = open('test2.txt','w')
str = 'hello world.n this is my first file handling
program.n I am using python language"
f.writelines(str)
f.close()
16. To access the contents of file randomly - seek and tell
methods are used.
tell() method returns an integer giving the current position
of object in the file. The integer returned specifies the
number of bytes from the beginning of the file till the
current position of file object.
It's syntax is
fileobject.tell()
seek()method can be used to position the file object at
particular place in the file. It's syntax is :
fileobject.seek(offset [, from_what])
here offset is used to calculate the position of fileobject in
the file in bytes. Offset is added to from_what (reference
point) to get the position. Following is the list of
from_what values:
Value reference point
0 beginning of the file
1 current position of file
2 end of file
default value of from_what is 0, i.e. beginning of the file.
17. So for storing data in binary format, we will use
pickle module.
First we need to import the module. It provides
two main methods for the purpose, dump and
load. For
creation of binary file we will use pickle.dump()
to write the object in file, which is opened in
binary access mode.
Syntax of dump() method is:
dump(object, fileobject)
Example:
def fileOperation1():
import pickle
l = [1,2,3,4,5,6]
file = open('list.dat', 'wb') # b in access mode is
for binary file
pickle.dump(l,file) # writing content to binary file
file.close()
22. Files are always stored in current folder / directory by
default. The os (Operating System) module ofpython
provides various methods to work with file and folder
/ directories. For using these functions, we have to
import os module in our program.
Some useful methods, which can be used with files in
os module are as follows:
path.abspath(filename) will give us the complete path
name of the data file.
path.isfile(filename) will check, whether the file exists
or not.
remove(filename) will delete the file. Here filename
has to be the complete path of file.
rename(filename1,filename2) will change the name of
filename1 with filename2.
23. Once the file is opened, then using file object,
we can derive various information about file.
This is done using file attributes defined in os
module. Some of the attributes defined in it
are
1. file.closed returns True if file is closed
2. file.mode returns the mode, with which file
was opened.
3. file.name returns name of the file
associated with file object while opening the
file.
24. os.chdir(path) Change the current working
directory to path.
os.getcwd() Return a string representing the
current working directory.
os.chmod(path, mode) Change the mode of
path to the numeric mode. mode may take
one of the following values (as defined in the
stat module) or bitwise ORed combinations of
them:
os.listdir(path) Return a list containing the
names of the entries in the directory given by
path. The list is in arbitrary order. It does not
include the special entries '.' and '..' even if
they are present in the directory.
25. s.mkdir(path[, mode]) Create a directory named path
with numeric mode mode. The default mode is 0777
(octal). On some systems, mode is ignored. Where it
is used, the current umask value is first masked out.
If the directory already exists, OSError is raised.
os.rmdir(path) Remove (delete) the directory path.
Only works when the directory is empty, otherwise,
OSError is raised. In order to remove whole directory
trees, shutil.rmtree() can be used.
os.rename(src, dst) Rename the file or directory src to
dst. If dst is a directory, OSError will be raised. stems.
If successful, the renaming will be an atomic
operation (this is a POSIX requirement).
On Windows, if dst already exists, OSError will be
raised even if it is a file; there may be no way to
implement an atomic rename when dst names an
existing file.
27. def fileHandling():
file = open("story.txt","w+") # both reading &
writing
choice = True
while True:
line = raw_input("enter sentence :")
file.write(line) # creation of file
choice = raw_input("want to enter more data in
file Y / N")
if choice == 'N' : break
file.seek(0) # transferring file object to beginning
of the file
lines = file.readlines()
file.close()
for l in lines:
print l