File Handling in Python

The key function for working with files in Python is the open() function. The open() function takes two parameters: filename, and mode. I have taken info.txt as my input file. 

Input file: [info.txt]

My Name is X
I am Y years old.
I live in Z.

There are two ways we can open a file. For this example I have chosen that my python file and input file are in the same folder. But if your python file and input file is not in the same directory, then you have give the full path of your input file.

1st Method:

with open('info.txt'as file:
  data = file.read()                # read() is used to read the data 
data = data.split("\n")             # split data at the end of line
for line in data:
  print(line)
file.close()                        # good practice to close file after file operation

Output:
My Name is X I am Y years old. I live in Z.

2nd Method:

file = open('info.txt' , 'r')       # open the file at read mode
data = file.read()                  # read() is actually reading the file
print(data)
file.close()                        # good practice to close file after file operation

Output:
My Name is X I am Y years old. I live in Z.

There are 4 different methods for opening a file.

“r”
Opens file for reading, error if file doesn’t exist
“a”
Opens file for appending, creates file if doesn’t exist
“w”
Opens file for writing, creates file if doesn’t exist
“x”
Creates the specified file, error if the file exists


Now suppose we want to add something to the input file. So we have to open info.txt at append mode and write what we want to write using the write method.

f = open("info.txt""a")           # open the file at append mode
f.write("My fathers name is A")     # write() method is used to write in a file
f.close()                           # good practice to close file after file operation

# open and read the file after the appending
file = open("info.txt""r")        # open the file at read mode
print(file.read())
file.close()                        # good practice to close file after file operation

Output:
My Name is X I am Y years old. I live in Z.My fathers name is A

If we want to overwrite the content of info.txt we can just open it in write mode.

f = open("info.txt""w")           # open the file at write mode
f.write("It's a new file")          
f.close()                           

#open and read the file after the writing
file = open("info.txt""r")
print(file.read())
file.close()

Output:
It's a new file

If we want to create a file that doesn't exist, we can use any one of the three commands below. The operations are
of course different and we can choose any one depending on our requirements.

file = open("newfile.txt""x") # create a file if doesn't exist
file = open("newfile.txt""a") # create a file if doesn't exist and go to append mode
file = open("newfile.txt""w") # create a file if doesn't exist and go to write mode

If we want to remove a file using python, we have to import a library called os.

import os
os.remove("newfile.txt")

If we are not sure, we can always check

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

Question: If I run the last code twice, what will happen?

So, that's it for python file handling.

Post a Comment

0 Comments