Monday, February 24, 2020

File Handling In Python

File Handling In Python

File handling operations like reading, writing, updating and delete the data in files of an operating system is very easy with Python We need a short piece of code to access a file in Python in comparison to other programming languages. Unlike other languages where file input and output operations require a complex process of reading and writing objects, this process is very simple in Python and requires only a few commands to open, read, write and close the file. This tutorial explains how Python can handle files on the operating system.

The open() Function

The main component to handle files in Python is the open() function. The open() function takes two parameters; filename, and the mode.

  • The filename is the path to the file or, if the file exists in the working directory, the name of that file
  • The mode a string value to determine how the file must be opened.

The Modes of File Access

There are different modes to open a file specified by this mode parameter.

  • 'r'- read mode is the default mode and allows us to simply read the file and not to modify the file.
  • 'w'- write mode creates file specified by the filename if it doesn't exist, otherwise, it will erase the file and permit you to write there.
  • 'a'- append mode allows us to write data to the top of the file. It doesn't erase the file, and therefore the file must exist for this model.
  • 'rb'- read mode in binary. this is often almost like ‘r’ mode except that the reading operation is forced in binary mode.
  • 'r+'- This read along with write mode simultaneously and allows us to read and write into files at the same time without having to use 'r' and 'w' separately.
  • 'rb+'- read and write mode in binary and this mode is equivalent to ‘r’ mode except the data is in binary format.
  • 'wb'- write mode in binary and an equivalent to ‘w’ except the info is in binary.
  • 'w+'- write and read mode. This is precisely the same as ‘r+’ but if the file doesn't exist, a replacement one is created else the same file is overwritten.
  • 'wb+'- write and read mode in binary mode and an equivalent as ‘w+’ but the info is in binary representation.
  • 'ab'- append mode in binary and almost the same as ‘a’ except that the info is in binary representation.
  • 'a+'- append and read mode and almost like ‘w+’.This will create a replacement file if the file doesn't exist.
  • 'ab+'- append and read mode in binary. It is equivalent to ‘ a+’ except that the data is in binary representation.
We can summerise the above modes in the following table,

r

r+

w

w+

a

a+

Read
Write
Creates file
Erases file

The Exclusive Modes


Python 3 introduced a new mode for exclusive creation so that you will not accidentally truncate or overwrite and existing file.

x

x+

Read
Write
Creates file
Erases file


  • 'x'-This mode opens in exclusive creation and it will raise FileExistsError if the file already exists.
  • 'xb'- This mode opens for exclusive creation write mode in binary format. The same as ‘ x’ except the data is in binary representation.
  • 'x+'- Exclusive read and write mode, It is equivalent to ‘w+’ and create a new file if the file does not exist. Otherwise, it will raise FileExistsError.
  • 'xb+'- Exclusive read and write mode. This is equivalent to ‘ x+’ but the data in a binary format.
For Example

#Write to the file
with open('myfile.txt', 'w') as f:
    f.write('this is the new file')
#Append to the file
with open('myfile.txt', 'a') as f:
    f.write('\\n Appended message is Python is easy')

print('written successfully')


#Read the file
with open('myfile.txt', 'r') as f:
    f.read()

#This can be done in a better way as 
try:
    with open("fname", "r") as fout:
    # Work with your open file
except FileExistsError:
    #Raise the error


Reading the File Line By Line


with open('myfile.txt', 'r') as fp:
    for line in fp:
        print(line)

The readlines() method


For more control over the data over the data we can use the readlines() method 

with open("myfile.txt", "r") as fp:
    lines =fp.readlines()

for i in range(len(lines)):
    print("Line "+ str(i)+ ": "+ lines[i])



to read the full content of the file the read() method can be used.

with open('myfile.txt') as fl:
    content =fl.read()
    print(content)

The write() Method

The write() method can be used to write the data into a file. We need to inserts line break (\n) character for a new line, as Python itself does not provide a new line character itself.

with open('myfile.txt', 'w') as f:
    f.write("Python is\n")
    f.write("Easy and\n")
    f.write("simple \n")
    f.write("programming language\n")
print('Written Successfully')