Python being an implicit and intuitive language allows the user to handle files relatively easier as compared to other programming languages. However, with the ease in manipulation and handling of files, Python also has some shortcomings that may impact the way files are handled and also introduces newer methods to amend those shortcomings.

Let’s take a look into the basic file operators in Python:

Opening & Closing Files

Python allows the user to conduct complete manipulation of files like any other programming languages and supports the four most basic functions of a file that are:

Opening

Reading

Writing

Closing

These four functions are then further divided into multiple branches that we will discuss later on. In order to open a file, Python has a built-in open() function that allows you to open a file, this is implicitly detected by Python and does not need an explicit declaration.

If your file is located in your Python file directory you don’t need to specify a path, like this:

f1 = open("file1.txt") #Opens the file if it is present in the current directory

If you have a file located somewhere other than your Python file directory then use this syntax:

f1 = open("C:/Users/Home/file1.txt") #You can specify the path for the file you have on your computer

There are many operators in Python for file handling that specify what you want to do once you have opened the file, here are some functions:

f1 = open("C:/Users/Home/file1.txt", 'r') #The 'r' is used for reading from a file, this will only read from the file.
f1 = open("C:/Users/Home/file1.txt", 'w') #The 'w' is used for writing to a file, this will only write to the file.

If you want to encrypt the data in a file for security purposes you can utilize the utf-8 encryption on your files to secure them adamantly:

f1 = open("C:/Users/Home/file1.txt", mode='w', encoding='utf-8') #Here we have explicitly defined all the constraints and parameters of the file.

Python automatically detects if a file has been opened and can simply utilize the close() function to close it and continue with the code. Since the function call is done implicitly, the placement of the file closer function has to be accurate.

f1 = open("C:/Users/Home/file1.txt", 'w')

f1.close() #This will close the file named 'f1'

In rare cases, if a file throws an exception or an error, Python will directly exit the code without closing the file which may mess-up the flow, which is why using the try and final method is more suited when it comes to closing files properly:

try:
     f1 = open("testfile.txt", mode = 'w', encoding = 'utf-8')

finally:
     f1.close() #The ‘try’ will execute the commands inside it and only when the executions are complete it will move on to the ‘finally’ clause.

Reading and Writing Files

We already know that the ‘r’ allows you to open a file for reading, but there are functions that allow the user to extract relevant data from the file such as read(), readline() and readlines(). Other functions include seek() and tell(), these are the most basic functions.

f1 =open("testfile.txt", mode = 'r', encoding = 'utf-8')

f1.read() # this will read all the data in the file

f1.read(10) # this will only read the first 10 characters including spaces.

f1.readline() # This function will only read the first line

f1.readlines() # this function will read all the lines until file reaches EOF state
f1.seek() # this will bring the cursor to whatever character you enter between the parenthesis

for line in f1:
    print(line, end = ' ') # this will utilise the for loop to read and print lines one-by-one.
    

Writing files in Python is also relatively easy, you can open a file using the ‘w’, ‘a’ or ‘x’ call and it will allow you to write content into the file. The command and its execution is relatively easy:

f1 = open("textreadme.txt", "w") # ‘W’ will open the file and write, if it doesn't exist, it will create a new one.

f1.write("This is new text")

f1.close()
f1 = open("textreadme.txt", "x") # 'X' will create the file and write, if it already exists, it will throw an error.

f1.write("This is new text")

f1.close()
f1 = open("textreadme.txt", "a") # 'a' will open the file and append content, if it doesn't exist, it will create a new one.

f1.write("This is new text")

f1.close()

The afore-mentioned blocks of code encompass the major parts of the file-handling operations in Python, there are many more options and functions that can be applied on files which can be further branched out into doing specific tasks with files.

Categorized in: