Files
Files
Why 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..
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.