File Handling

File handling is an important part of any web application. Python has several functions for creating, reading, updating, and deleting files.

PYTHON FILE OPEN

The key function used for working with files in Python, is open() function. The open() function takes two parameters:  filename and mode. There are four different methods (modes) for opening a file:

“x” = Create – Creates the specified file, returns an error if the file exists.

“w” = Write – Opens a file for writing, creates the file if it does not exist, but in general replace or overwrite previous data with current one in that file

“r” = Read- Default value. Opens a file for reading, shows error if the file does not exist.

“a” = Append – Opens a file for appending, creates the file if it does not exist, but in general used for adding data to that file.

In addition you can specify if the file should be handled as binary or text mode.

“t” = Text – Default value. Text mode.

“b” = Binary – Binary mode(e.g. images)

1. CREATE A NEW FILE IN PYTHON

To create a new file in Python, use the open() method, using the following parameters.

“x” – Create – will create a file, returns an error if the file exist

# New empty file called “myfile.txt” is created.

f = open("myfile.txt", "x")

OUTPUT:

CREATE FILE IN PYTHON
OUTPUT – CREATE FILE IN PYTHON

2. WRITE TO AN EXISTING FILE IN PYTHON

To write to an existing file, you must add a parameter to the open() function.

“w” – Write – will overwrite any existing content

Open the file “myfile.txt” in write mode and insert some data.

f = open("myfile.txt", "w")
f.write("""Content has been written!
        This is second line
        This is Third line""")
f.close()

OUTPUT:

WRITE IN EXISTING FILE IN PYTHON
OUTPUT – WRITE IN EXISTING FILE IN PYTHON

3. READ AN EXISTING FILE IN PYTHON

To open a file for reading it is enough to specify the name of the file:

Syntax:  f = open(“myfile.txt”)

To read a file we give a command: f = open(“myfile.txt”, “rt”)

where, ‘r’ for read ‘t’ for text are the default values.

Assume we have the following file, located in the same folder as Python:

To open the file, use the built-in open() function. The open() function returns a file object, which has a read() method for reading the content of the file.

3.1 READ FILE IN PYTHON

f = open("myfile.txt", "r")
print(f.read())

OUTPUT:

READ FILE IN PYTHON
OUTPUT – READ FILE IN PYTHON

3.2 READ ONLY A PART OF THE FILE IN PYTHON

By default the read() method returns the whole text, but you can also specify how many characters you want to return.

For example:

f = open("myfile.txt", "r")
print(f.read(5))

OUTPUT:

READ ONLY A PART OF FILE IN PYTHON
OUTPUT – READ ONLY A PART OF FILE IN PYTHON

3.3 READ LINES OF THE FILE IN PYTHON

You can return one line by using the readline() method.

f = open("myfile.txt", "r")
print(f.readline())

OUTPUT:

READ ONE LINE OF FILE IN PYTHON
OUTPUT – READ ONE LINE OF FILE IN PYTHON

3.4 READ TWO LINES OF THE FILE IN PYTHON

By calling readline() two times, you can read the FIRST two lines of the file. 

f = open("myfile.txt", "r")
print(f.readline())
print(f.readline())

OUTPUT:

READ TWO LINE OF FILE IN PYTHON
OUTPUT – READ TWO LINE OF FILE IN PYTHON

3.5 READ THE WHOLE FILE, LINE BY LINE IN PYTHON

By looping through the lines of the file, you can read the whole file, line by line.

f = open("myfile.txt", "r")
for x in f:
    print(x)

OUTPUT:

READ FILE LINE BY LINE IN PYTHON
OUTPUT – READ FILE LINE BY LINE IN PYTHON

4. APPEND “A” IN FILE IN PYTHON

“a” – Append – will append to the end of the file

Open the file “myfile.txt” and append content to the file.

f = open("myfile.txt", "a")
f.write(" Now the file has more content!")
f.close()

#open and read the file after the appending:
f = open("myfile.txt", "r")
print(f.read())

OUTPUT:

APPEND OR ADD IN FILE IN PYTHON
OUTPUT – APPEND OR ADD IN FILE IN PYTHON

5. OVERWRITE THE FILE IN PYTHON.

Open the file “myfile.txt” and overwrite the content.

f = open("myfile.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the appending:
f = open("myfile.txt", "r")
print(f.read())

OUTPUT:

OVERWRITE IN FILE IN PYTHON
OUTPUT – OVERWRITE IN FILE IN PYTHON

6. CLOSE FILES IN PYTHON

It is a good practice to always close the file when you are done with it.

f = open("myfile.txt", "r")
print(f.read())
f.close()

OUTPUT:

CLOSE FILE IN PYTHON
OUTPUT – CLOSE FILE IN PYTHON

7. CHECK IF FILE EXISTS IN PYTHON

To avoid getting an error, you might want to check if the file exists before you try to delete it. You must import the OS module.

import os
if os.path.exists("myfile.txt"):
    print("The file Found")
    #os.remove("myfile.txt")
else:
    print("The file does not exist")

OUTPUT:

CHECK FILE PRESENT IN PYTHON
OUTPUT – CHECK FILE PRESENT IN PYTHON

8. DELETE A FILE IN PYTHON

NOTE: CHECK IF FILE EXISTS, THEN DELETE FILE IN PYTHON

To delete a file, you must import the OS module, and run its os.remove() function:

import os
if os.path.exists("myfile.txt"):
    print("The file Found and removed")
    os.remove("myfile.txt")
else:
    print("The file does not exist")

OUTPUT:

DELETE FILE IN PYTHON
OUTPUT – DELETE FILE IN PYTHON

If you re-run the program

OUTPUT:

CHECK DELETE FILE IN PYTHON
OUTPUT – CHECK DELETE FILE IN PYTHON

Leave a Reply

Your email address will not be published. Required fields are marked *