File Handling in Python and modes in it.



What is file handling in Python:


File handling is an important part of any web application.

Python has number of functions in file handling:

  • creating
  • editing
  • deleting
  • reading 
  • the files.

Key function is open()


How is open() function in Python?

- open() has 2 parameters 
file name
modes.

What are different modes in Python for open() function:

"r" - Read - Default value. Opens a file for reading, and shows error if the file does not exist

"x" - Create - Creates the specified file, returns an error if the file already exist

"w" - Write - Opens a file for writing and a new file is created if it does not exist

"a" - Append - Opens a file for appending, and a new file is created if it doesnt exist.

How to define the way file should be handled in Python:
in python you can define how the file can be handled:

"t" - Text - Default value. Text mode 
"b" - Binary - Binary mode (e.g. images, other than text)


if the file is already exists; then to open the file what is the syntax used in Python:

if the file is already exists then you can use below syntax:

f = open("filename.txt")

rt  are default here so no need to mention it in syntax. "r" for read, and "t" for text, 
f = open ("filename.txt", "rt")-- is not required here.

Happy learning!





 

Comments