top of page

Python File - Handling

Python supports different types of file handling options, to operate on file, which is given below:

 

  • r - It is used for reading the file.

  • w - It is used for writing the file.

  • a - It is used for appending the file.

  • r+ - It is used for both reading and writing the file

 

If you do not pass any option then it works by using r option(By default)

 

Here we can learn it with the help of some codes of lines –

Read Option

“r” option is used to read file

>>> File = open(“filename”, “r”)

.

.

File.close()

Write Option

“w” option is used to read the file

>>> File = open(“filename”, “w”)

.

.

File.close()

Append Option

“a” option is used to read the file

>>> File = open(“filename”, “a”)

.

.

File.close()

Open file using “with” option and “write” into the file

>>>  with open(“filename”, “w”) as f:

                f.write(“hello naveen”)

Split lines using file hadling

To perform this we have used the split() function with filehandling

>>>  with open(“filename”, “r”) as f:

                for line in f:

                   data = line.readlines()

                    result = data.split()

                f.write(“hello naveen”)

This is the last tutorials of this python series, I hope it helpful for all beginner and professional developers if you like then please give an comments in below so that we can try to organized tutorials as per your choice. 

bottom of page