File Handling

What is the importance of file handling? Explain the mechanism of file handling in Python.

Python language supports two types of files. The first one is a text file that store data in the form of text and readable by humans and computers. The second one is binary file that store binary data and readable by computer only.

What are file attributes? Explain the file attributes provided by Python.

In Python,the files are accessed using open() function.If the file is opened successfully, the file object is returned.
If the file is not opened , the IOERROR exception is raised.The open function takes 3 arguments.
The first argument is the name of the file, the second the mode in which the file is opened and the third indicates the buffer string.

Explain various file access modes.

The access mode is the mode in which the file will be opened.
The various modes have been listed as below:

File ModeOperations
<p>r</p>reading from a file
<p>w</p>write to a file; creates the file if it does not exist; truncate the file if it already exists.
<p>a</p>append to the file; if the file does not exist this creates the file
r+open for read and write
w+w for both read and write
a+a for both read and write
<p>rb</p>read a binary file
<p>wb</p>write mode for a binary file
<p>ab</p>append mode for a binary file
rb+r+ for a binary file
wb+w+ for a binary file
ab+a+ for a binary file

Important Points:

  • The open function takes three arguments.
  • The mode of opening file decides the tasks that can be accomplished.
  • The file should be closed after the required task has been completed.
  • The seek method helps to move the cursor within a file.
  • The file name attribute prints the name of the file.
  • The file mode attribute gives the file access mode.
  • The os.getpwd function returns the present working directory.
  • The os.chdir function changes the directory.
  • Following are a solid argument for using file handling:
    1. It is not possible to store all data produced by the program in the main memory
    2. It is used for persistent storage

Open a file called “cloudvikas.csv” in the read mode. Check the name of the file, its mode, and find whether it is closed using the file attributes.
Solution:


f=open('cloudvikas.csv','r')
print('Name of the file\t:',f.name)
print('Mode\t:',f.mode)
print('File closed?\t:',f.closed)
f.close()
print('Mode\t:',f.mode)
print('File closed?\t:',f.closed)

Output

Name of the file : cloudvikas.csv
Mode : r
File closed? : False
Mode : r
File closed? : True
>>>
 
Sort the numbers entered as the command line arguments(using bubble sort).


import sys
def sort(L):
   i=0;
   while(i<(len(L)-1)):
      print('\nIteration\t:',i,'\n');
      j=0
      flag=0
      while(j<(len(L)-i-1)):
      if(L[j]<L[j+1]):
        flag=1
        temp=L[j]
        L[j]=L[j+1]
        L[j+1]=temp
      #print(L[j],end=' ')
      j=j+1
    print(L)
    if(flag==0): break
    i=i+1
  return(L)
L=[]
for x in sys.argv:
   L.append(x)
print('Before sorting\t:',L)
print(sort(L))

Write a program to ask the person to enter lines of text. The person should be able to enter any number of lines. In order to stop, he must enter “\f.” The lines should be appended to an empty list (say L). This list should then be written to a file called subject.txt. The program should then read the lines of subject.txt.
print('Enter text, press \'\\f\' to exit')
L=[]
i=1
in1=input('Line number'+str(i)+'\t:')
while(in1 !='\f'):
   L.append(in1)
   i=i+1
   in1=input('Line number'+str(i)+'\t:')
print(L)
f=open('Subject.txt','w')
f.writelines(L)
f.close()
f=open('subject.txt','r')
for l in f.readline():
   print(l, end=' ')
f.close()>>>
Output

Enter text, press '\f' to exit
Line number1 :Hi there
Line number2 :How are you
Line number3 :I am good
Line number4 :\f
['Hi there', 'How are you', 'I am good']
Hi there How are youI am good
Write a program to copy the contents of one file to another.
# open both files
with open('C:/Users/Vikas/Desktop/ebook/first.txt', 'r') as firstfile, open('C:/Users/Vikas/Desktop/ebook/second.txt', 'a') as secondfile:
    # read content from first file
    for line in firstfile:
        # append content to second file
        secondfile.write(line)
Write a program to capitalize the first character of each word in a file.
file_gfg = open('C:/Users/Vikas/Desktop/ebook/first.txt', 'r')
for line in file_gfg:
    output = line.title()
    print(output)
Frequency of each character in String.
test_str = "cloudvikasiscloud"
  

res = Counter(test_str) 
  
# printing result  
print ("Count of all characters in test_str is :\n "
                                           +  str(res)) 
Open a file Subject.txt and write a few lines in it. Now open the file in the read mode and read the first 25 characters from the file. Then read the next ten characters. In each step show the position of the cursor in the file. Now, go back to the first position in the file and read 30 characters from the file.
f=open('Subject.txt','w')
f.writelines(['Python java', 'Are imp lang'])
f.close()
f = open('Subject.txt', 'r+')
str = f.read(25)
print('String str\t: ', str)
pos = f.tell()
print('Current position\t:', pos)
str1=f.read(10)
print('Str1\t:',str1)
pos = f.seek(0, 0)
print('Current position\t:',pos)
str = f.read(30);
print('Again read String is : ', str)
f.close()
  1. To be able to use a file it must be opened. The reason for doing so is
    1. To allocate memory to the object formed
    2. To specify the access mode
    3. To specify the offset (optional)
    4. All of the above

Answer:(d)

In f = open(“abc.txt”, “r”), the offset is

a. 0 from the beginning
b. 0 from the end
c. Random
d. None of the above
Answer:(a)

The file must be closed if it is opened in which of the following modes?

a. r
b. w
c. Both
d. None of the above
Answer:
(c)

Which of the following arguments in the seek() function denotes the end of the file?

a. 1
b. 2
c. 0
d. None of the above
Answer:(b)

The linesep function is used to find which of the following?
a. The new line
b. The end of the file
c. The current directory
d. None of the above
Answer:(a)

To read all the lines in a file, which of the following functions can be used?

a. readline ()
b. readlines ()
c. Both
d. None of the above
Answer:
(b)

Which of the following methods can be used to write a list of strings in a file?

a. writeline ()
b. writelines ()
c. write ()
d. None of the above
Answer:
(a)

Which of the following is not a file attribute?
a. Closed
b. Opened
Answer:
(b)

In which of the following variables is the command line argument saved?
a. argv
b. argc

Answer:
both

Which function returns the descriptor of the file?
a. fileno ()
b. filedisp()
c. descriptor ()
d. None of the above
Answer:(a)

Which of the following functions helps to change the current directory?
a. os.mkdir()
b. os.chdir()
Answer:(b)

Which of the following functions helps to create a directory?
a. os.mkdir()
b. os.chdir()
Answer:(a)

Which of the following functions helps to print the name of the current directory?
a. os.mkdir()
b. os.chdir()
c. os.getpwd()
Answer:
(c)

Which suffix is used for opening a binary file

a. b
b. bin
c. ab
d. None of the above
Answer:
(a)

Which function is used to find the ASCII value of a character?
a. ascii
b. ord
Answer:(b)

The + suffix allows

a. Read
b. Read and write
c. Read or write
d. None of the above
Answer:
(b)

How many file access modes are there in Python?

a. 3
b. 6
c. 9
d. 12
Answer:
(c)

Which of the following is not a file access mode in Python?
a. a
b. ab
c. ab+
d. abc
Answer:
(d)