Showing posts with label File Handling. Show all posts
Showing posts with label File Handling. Show all posts

Aug 29, 2020

File Handling in Python | PYTHON LANGUAGE | Coding Winds


Python File Handling

File handling is an important part of any web application. Generally, we divide files in two categories, text file and binary file. Text files are simple text whereas the binary files contain binary data which is only readable by computer.

 

File Opening

To open a file we use open() function. It requires two arguments, first the file path or file name, second which mode it should open.


There are four different methods (modes) for opening a file:

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

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

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

 

As we know file should be handled as binary or text mode

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

 

Example,


We can also neglect “r” and “t” as they are default values.

We can also specify the exact path of the file in as same.


File reading        


To read the whole file at once we use, read().


If you call read() again it will return empty string as it already read the whole file.

readline() can help you to read one line each time from the file.


To read all the lines in a list we use readlines() method.

 

Let us write a program which will take the file name as the input from the user and show the content of the file in the console.

As you see we used close().

Note: - All examples above, I haven’t mentioned about closing of a file, but its important in each and every case.

Always make sure you explicitly close each open file, once its job is done and you have no reason to keep it open. Because

·       There is an upper limit to the number of files a program can open. If you exceed that limit, there is no reliable way of recovery, so the program could crash.

·       Each open file consumes some main-memory for the data-structures associated with it, like file descriptor/handle or file locks etc. So you could essentially end-up wasting lots of memory if you have more files open that are not useful or usable.

·       Open files always stand a chance of corruption and data loss.

Note :- Using with statement will look over the file closing weight.


File writing

Let us open a file then we will write some random text into it by using the write() method. We can also pass the file object to the print function call, so that it writes in the file.