Python Programming - File Functions

You can learn about Python File Processing Programs with Outputs helped you to understand the language better.

Python Programming – File Functions

Different file functions are discussed in the following sections.

open ( )

In Python, a physical file must be mapped to an ing section. built-in file object with the help of the built-in function open ( ).

file_object = open(filename[, accessmode] [, buffersize] )
Python has in-built functions to create and manipulate files. The io module is the default module for accessing files and you do not need to import it. The module consists of open(filename, access_mode, buffer size) that returns a file object, which is called “handle”. You can use this handle to read from or write to a file. Python treats the file as an object, which has its own attributes and methods.

In the open( ) method, the first parameter is the name of a file including its path. The file path is a string that represents the location of a file. The access mode parameter is an optional parameter that decides the purpose of opening a file, i.e., read, write, append, etc. The optional buffer size argument specifies the file’s desired buffer size: 0 means unbuffered, 1 means line buffered.

If the path is in the current working directory, you can just provide the filename, as shown below: file object = open(“textfile.txt”)
If the file resides in some other directory, you have to provide the full path with the file name. Make sure the file name and path given are correct, otherwise you will get a FileNotFoundError.

close ( )

It closes the opened file. The file once closed, cannot be read or written to. For example,
my_file = open(“C:/Documents/python/abc.txt”, ‘r’)
print(my_file.read( ) )
my_file.close( )
my_file = open(“C:/Documents/Python/xyz.txt”, ‘w’)
my_file.write(“Hello”)
my_file.close( )

read ( )

To read a file Python provides the read() method. The read ( ) method reads a string from the file. It can read the data in the text as well as binary format. When you read the file with read ( ), you read strings from the file. When you read numbers, you need to convert them to integers with data type conversion functions like int ( ).

  • read ( ) reads at a specified number of bytes from the file.

Example
Deno of read ( ) function.

# Demo of read() function
my_file = open(“c:/Documents/Python/abc.txt”,”r”)
print(my_file.read( ))RUN
>>>
This is the first sentence of the code.
This is the second sentence of code.
This is the third sentence of the code.
>>>

Let’s Try

# Reading the entire file at once
my_file = “c:/Documents/Python/abc.txt”
file_handle = open(my_file, ‘r’)
file_data = file_handle.read ( )
print(file_data)

In order to read a character from the file, you can pass the argument to the read ( ) function, for example, read(22) would read the first twenty-two characters of the file. Let’s understand the sample code given in figure 11.4.

Example
Program to read first 22 characters from file.

#Program to read first 22 characters from file
my_file = open (“c:/Documents/Python/abc. txt”,”r”)
print(my_file.read(22) )RUN
>>>
This is the first sentence
>>>

Let’s Try

#Program to read first few characters from file
my_file = open(“c:/Documents/Python/abc.txt”,”r”)
print ( my_file . read ( 4 ) )

readline ( )

Python enables us to read the file line by line by using a function readline ( ). It reads one line from the file and places the file pointer to the beginning of the new line. If you use the readline ( ) method twice, then you get the first two lines of the file.

Example
Demo of readline ( ) function.

# Demo of readline( ) function
myfile = open(“c:/Documents/Python/abc.txt”,”r”)
print ( my_file . readline ( ) )
print ( my_file . readline ( ) )
print ( my_file . readline ( ) )RUN
>>>
This is the first sentence of code.
This is the second sentence of code.
This is the third sentence of code.
>>>

readlines ( )

Another way you could iterate over each line in the file is to use the Python readlines ( ) method of the file object. The readlines ( ) reads all lines until the end of the file and returns a list object. readlines ( ) reads until EOF and returns a list containing the lines. (See Figure 11.6).

Example
Demo of readlines( ) function.

# Demo of readlines() function
myfile = open(“c:/Documents/Python/abc.txt”,”r”)
print ( my_file . readlines ( ) )RUN
>>>
[‘This is the first sentence of code.\n’, ‘This is the second sentence of code.\n’, ‘This is the third sentence of code.\n’]
>>>

readline ( ) function reads all the lines of the next file including the newline characters. In figure 11.7, you are trying to read only the 3rd line from the “abc.txt” file using a loop.

python provides a string method called strip ( ) which removes whitespace, or non-printable characters, from both ends of a string.

Example
Program to read a specific line from a File.

# Program to read a specific line from a File
line_number = 3
my_file = open(“c:/Documents/Python/abc.txt”,”r”)
current_line = 1
for line in my_file:
if(currentline == linenumber):
print(line)
break
current_line = currentline +1RUN
>>>
This is the third sentence of the code.
>>>

Let’s try

# First open the file to read(r)
inp = open(“c:/documents/python/abc.txt”,”r”)
# read the file into a list then print each item
for line in inp.readlines( ):
print (line)
# Now close it
inp.close( )

write ( )

The write( ) function writes a fixed sequence of characters to a file. The write ( ) does not actually write data to a file but to a buffer. When the close ( ) function is called, it is written in the file.

In order to write data into a file, you must open the file in write mode.

You need to be very careful while writing data into the file as it overwrites the content present inside the file that you are writing, and all the previous data is erased. Before writing data to a sample.txt file, the file appears as shown in Figure 11.8.

Python Programming - File Functions chapter 11 img 1

Now write one sentence using write ( ) function as given in example 8.

Example
Demo of write( ) function.

# Demo of write() function
myfile = open(“c:/Documents/python/sample.txt”,”w”)
my_file.write(“I am writing my first sentence”)
my_file.close ( )

The above code writes the string “I am writing my first sentence” into the “sample.txt” file. Now the sam-ple.txt file will be displayed as shown in Figure 11.10.
Note that the first line in Figure 11.11 is “I am writing my first sentence \n” ending with \n character, the cursor will move to the next line of the file and then write “I am writing my second sentence”. Remember if you do not mention \ n character, then the data will be written continuously without any space in the text file.

Python Programming - File Functions chapter 11 img 2

Example
Demo of write ( ) function.

# Demo of write( ) function in the file sample.txt
my_file = open(“c:/Documents/python/sample.txt”,”w”)
my_file.write(“I am writing my first sentence\n”)
my_file.write(“I am writing my second sentence”)

Python Programming - File Functions chapter 11 img 3

writelines ( )

The writelines writes a sequence of the strings to a file. It’s syntax is :
file_object . writelines (seq)
so, wherever you have to write a sequence of string , you will use writelines ( ) , instead of write ( ). ( see figure 11. 13 )

Example
Demo of writelines ( ) function.

# Demo of writelines ( ) function to write list of data
colours = [“Red\nM, “Blue\n”, “Green\n”f “Yellow”]
my_file = open(“C:/Documents/python/test.txt”, “w”)
my_file.writelines(colours)
my_file.close ( )

The output of the program shown 11.13 is shown in figure 11.14

Python Programming - File Functions chapter 11 img 4

append ( )

Appending is writing data at the end of the file. In this mode, the file pointer is placed at the end an existing file. It can also be used for creating a file, by opening a nonexisting file using this mode. In order to write into a file in Python, you need to open it in write ‘we, append ‘a’ or exclusive creation ‘x’ mode. You need to be careful with the ‘w’ mode as it will overwrite into the file if it already exists. All previous data are erased. Writing a string or sequence of bytes (for binary files) is done using the write ( ) method. This method returns the number of characters written to the file.
Let’s see how the append mode works:
To append data into a file you must open the file in “a+” mode so that you have access to both append as well as write modes.

Example
Demo of append ( ) function.

# Demo of appending string
my_file = open(“C:/Documents/python/test.txt”, “a+”)
my_file . write ( “\nPink”)
my_file . close ( )

The output of the program shown in Figure 11.15 is shown in Figure 11.16. Note that the code in Figure 11.15 appends a string “pink” into a “test.txt” file.

Python Programming - File Functions chapter 11 img 5

Example
Demo of appending list of data.

# Appending list of data in the file test.txt
colours = [“\nWhite”, “\nBlack”, “\nIndigo”, “\nPurple”]
my_file = open(“C:/Documents/python/test.txt”, “a+”)
my file.writelines(colours)
my file.close ( )

The output of the program shown in figure 11.17 is shown in figure 11.18.

Python Programming - File Functions chapter 11 img 6

tell ( )

The tell ( ) method tells the current position within the file; in other words, the next read or write will occur at that many bytes from the beginning of the file.

  • The tell ( ) method is used to print the byte number at which the file pointer exists.

seek ( )

The seek ( ) method enables you to modify the file pointer position externally.
The syntax to use the seek() method is:
<file-ptr>.seek(offset[, from_what) offset refers to the new position of the file pointer. from_what shows the reference position from where the bytes are to be moved. The reference point 0 indicates the beginning of the file and is the default, 1 (the current position of file) and 2 (the end of the file).

  • seek ( ) sets the file’s current position.

Example
Demo of tell ( ) and seek ( ) methods.

# Demo of tell() and seek() methods
text= [11 \nDif f erent” , “Colours” , “Name”]
my_file = open(“C:/Documents/python/test.txt”, mode=”a+”)
my_file.writelines(text)
print(“Position of the file cursor ,my_file.tell())
my_file.seek(0)
for line in my_file:
print(line)RUN
>>>
Position of the file cursor: 88
Red
Blue
Green
Yellow
Pink
White
Black
Indigo
PurpleDifferentColoursName
>>>

rename ( )

Python provides us with an “os” (Operating System) module which has some in-built methods that would help us in performing the file operations such as renaming and deleting the file. In order to use this module, first of all, you need to import the “os” module in your program and then call the related methods.

This rename( ) method accepts two arguments i.e. the current file name and the new file name. Its syn-tax is:
os.rename(current_file name, new_file_name)
You can specify the location as well as shown in example 14.

Example
Demo of rename() function.

# Demo of rename ( )
import os
os.rename(“C:/Documents/python/test.txt”, “C:/Documents/python/testl.txt”)

remove ( )

The remove ( ) method is used to delete the file by supplying the file name or the file location that you want to delete. Its syntax is:
os.remove(filename)

For example:
import os
os.remove(“test.txt”)
Here “test.txt” is the file that you want to remove. Similarly, you can pass the file location as well to the arguments as shown in the example:

import os
os.remove(“C:/Documents/Python/ test.txt”)

Leave a Reply

Your email address will not be published. Required fields are marked *