0% found this document useful (0 votes)
1 views31 pages

Files

The document discusses file handling in programming, emphasizing the importance of files for permanent data storage beyond program execution. It outlines various file operations such as creating, opening, reading, writing, and closing files, along with different modes for file access. Additionally, it provides examples of reading and writing text and numeric data to files, as well as methods to ensure data integrity when handling existing files.

Uploaded by

colab178178
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views31 pages

Files

The document discusses file handling in programming, emphasizing the importance of files for permanent data storage beyond program execution. It outlines various file operations such as creating, opening, reading, writing, and closing files, along with different modes for file access. Additionally, it provides examples of reading and writing text and numeric data to files, as well as methods to ensure data integrity when handling existing files.

Uploaded by

colab178178
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

File handling

Why file?

• Data stored in the program are temporary;


• They are lost when the program terminates.
• To permanently store the data created in a program, we need to save
them in a file on a disk or other permanent storage.
• The file can be transported and can be read later by other programs.
• There are two types of files:
text
binary.
• Text files are essentially strings on disk.
What is a file?

• A file is a collection of records.


• A record is a group of related data items.
• File is a named location on disk to store related information.
• File is used to permanently store data in a non-volatile memory (e.g. hard
disk) because random access memory (RAM) is volatile which loses its
data when computer is turned off, we use files for future use of the data.
• The data stored in a file is used to retrieve the user’s information either in
part or whole.
• we can use a file to store data permanently; or we can use exception
handling to make your programs reliable and robust.
File operations

Following is the list of file operations


1. Creating a file
2. Opening a file
3. Reading from a file
4. Writing to a file
5. Closing a file
Text input and output - How to open a file?

• A file is need to be open before we can perform read and write operations on
it.
• To open a file, a user needs to create a file object which is associated with
physical file.
• When opening a file , a user has to specify the name of the file and its mode
of the operation.
• We use open () function in Python to open a file in read or write mode.
Syntax :
file_variable= open(file_name, mode)
Different modes to open a file
The open function returns a file object for filename. The mode parameter is a string that specifies how the file
will be used (for reading or writing),
• “ r “ – Open a file for reading.
• “ w “ – Open a new file for writing, if already exists , its content are destroyed
• “ a “ - Open a file for appending data from the end of the file
• “Wb” - Open a file for writing binary data.
• “Rb” - Open a file for reading binary data.
Example :
file1 = open(“d:\hello.txt” , ”r” )
this command opens hello.txt in read mode.
• We can also use the absolute filename to open the file in Windows, as follows:
input = open(r"c:\pybook\Scores.txt", "r")
• The open function creates a file object, which is an instance of the
_io.TextIOWrapper class.

• This class contains the methods for reading and writing data and for closing
the file

•After a file is opened for writing data, you can use the write method to write a string to
the file.
Writing text to a file
• To write the text into a file , we must open a file in write mode.
• After opening the file by using write() methods we write the content into the file.
• After completion of writing the data we must close a file by using close() method
Ex: program writes three strings to the file
Presidents.txt

•The program opens a file named Presidents.txt using the w mode for writing data (line 3). If the file does not exist,
the open function creates a new file.
•If the file already exists, the contents of the file will be overwritten with new data. You can now write data to the
file.
The program invokes the write method on the file object to write
three strings (lines 6–8). Figure 13.2 shows the position of the file
pointer after each write.

Output:
Testing a File’s Existence
• To prevent the data in an existing file from being erased by accident, we
should test to see if the file exists before opening it for writing.
• The isfile function in the os.path module can be used to determine
whether a file exists. For example:
Reading text from a file
• Once file is opened using the open() function , its content is loaded into
the memory.
• To read the content of the file, we open the file in ‘r’(read) mode.
• There are several ways to read the content of the file.
• read() : use read() method to read all the data from a file and return
as one complete string.
• readlines(): use readlines() method to read all data and return as a list
of string.
• readline(): use readline() method to read the first line of the file
Reading text from a file ----using
read()

O/p:

O/p:
Reading text from a file ----using
readline()
O/p:

O/p:

O/p:
Reading text from a file ----using
readlines()

O/p:

O/p:
Suppose the file Presidents.txt contains the three lines shown in Figure
13.3. The program in Listing 13.2 reads the data from the file.
•The repr(s) function returns a raw string for s, which causes the escape sequence to be displayed as literals,
as shown in the output
Reading All Data from a File
• Programs often need to read all data from a file.
• Here are two common approaches to accomplishing this task:
• 1. Use the read() method to read all data from the file and return it as
one string.
• 2. Use the readlines() method to read all data and return it as a list of
strings.
• These two approaches are simple and appropriate for small files, but
what happens if the file is so large that its contents cannot be stored in
the memory? You can write the following loop to read one line at a time,
process it, and continue reading the next line until it reaches the end of
the file:
Contd..

We can also read file using for loop

It will be much simpler than while loop


Reading text from a file --- using for loop
Listing 13.3 illustrates a program that copies data from a source file to a target file and counts
the number of lines and characters in the file. LISTING 13.3 CopyFile.py
explanation
• The program prompts the user to enter a source file f1 and a target file f2 (lines 6–
7) and determines whether f2 already exists (lines 10–12).
• If so, the program displays a message that the file already exists (line 11) and exits
(line 12).
• If the file doesn’t already exist, the program opens file f1 for input and f2 for
output (lines 15–16).
• It then uses a for loop to read each line from file f1 and write each line into file f2
(lines 20–23).
• The program tracks the number of lines and characters read from the file (lines 21–
22).
• To ensure that the files are processed properly, you need to close the files after
they are processed (lines 26–27)
Append Data to a File
• we can use the a mode to open a file for appending data to the end of
an existing file

Before appending

After appending
Append Data to a File
Writing and Reading Numeric
Data
• To write numbers to a file, you must first convert them into strings and
then use the write method to write them to the file.
• In order to read the numbers back correctly, separate them with
whitespace characters, such as " " or \n.
• Write a program writes ten random single digits to a file and reads
them back from the file.
LISTING 13.5 WriteReadNumbers.py

Output:
explanation
• The program opens a file named Numbers.txt using the w mode for writing
data to that file using the file object outfile (line 5).
• The for loop writes ten numbers into the file, separated by spaces (lines 6–
7).
• Note that the numbers are converted to strings before being written to the
file.
• The program closes the output file (line 8) and reopens it using the r mode
for reading data through the file object infile (line 11).
• The read() method reads all data as a string (line 12).
• Since the numbers are separated by spaces, the string’s split method splits
the string into a list (line 13).
• The numbers are obtained from the list and displayed (lines 14–15).
Writing numbers to a file
Writing numbers to a file
• By default write() method expects a string as argument.
• In order to write integer or float data into a file using write() method
first we convert it into string.
Write a python program to generate
50 random numbers and store them
in a file.

You might also like