There are a few built-in functions in Python library to control external files in the program. External text files can be opened to read, write, close or append as per the need of the user. For these functions, there is no need to import additional modules. Now let us discuss a few key terms in handling files in Python.
Before we control the files, we need to first open the file using Python's inbuilt function open(). This open() function is generally assigned to a file handle which can further be used for various operations.
1) Open(): The open() function is used to open files in the user's system. This function takes in 2 parameters: 1. the name of the file and 2. the mode in which the file needs to be operated. i.e read "r", write "w" or append "a". If there is no mode specified, it is assumed to open the file in reading "r" mode by default.
2) Write(): Write enables us to embed a sequence of strings into a file. write() enables us to embed a sequence of characters into a while whereas writelines() enables us to write a list of strings to the file.
3) Append(): Append() function is used to append a file instead of overwriting the file with new information. To append an existing file we open the file in appending mode "a".
Consider the following example to analyse better,
Task: Write a program to open a notepad file called "faceprep.txt and print all the data in it.
file_name = "faceprep.txt" file_handle = open(file_name, "r") # Note: file_handle is not the data, but this can be used to extract and print the data. for line in file_handle: # 'line' is a variable, in each iteration a line is read and then printed. print line
Task: Count the number of lines in user specified file in the system.
f_name = input('enter filename')
f_handle= open(f_name) # if no mode is specified, read mode is automatically chosen by default
count=0 #initial count value is zero.
for line in f_handle: # for every line in the file
count +=1 # increment the count by 1 count+=1 is nothing but count=count+1
print(count) # print the final count value.