File input-output (I/O) and file handling in python.

What is File? It is a persistent memory on disk.  You may also manually create, delete, or edit a file. It can be of two types one is binary another is text.

File input and output in python is to get input in a program from a file and write output to the same of different file. In an earlier tutorial for python I/O we have learned how a user can provide input using a keyboard and how the program, displays output to the console (standard output).  For that, we learned about two functions print() and input().

In this tutorial, we will learn about another way for input-output. In this, a program reads the input from a file and writes the output to the file.  Unlike the standard I/O, the process is not interactive.  With file-based  I/O, a programmer may away from the console while in another he has to be present and enter values from the keyboard and note values from the screen.

The most common example of file handling is application logs.  When an application executes, it writes the logs to the file for events and another program may read logs to generate alarms for error events.

What python provides for file handling?

  • Open a file, new or existing.
  • Reading from a file.
  • Writing to a file.
  • Modify a file.
  • Closing a file.

Open a file(new or existing):

Prototype Object open(fileName(M), accessMode(O));      Here M- Mandatory, O-Optional

Python provides the open() function to open a file. It takes two arguments and returns an object to the file. The first argument is the file name and another is access mode.  With the return object, we can perform operations (read, write, etc.) on an opened file. AccessMode is optional, if not given, the file is opened in reading mode.

File Access Mode in python: 

  • (‘r’ ) –  Read mode (default), open fails if the file do not exist.
  • (‘w’ ) –  Write mode, opens a new file, if it does not exist. Else remove all contents of the existing file.
  • (‘x’ ) –  Exclusive creation, Fails if file exists.  Useful when always want to open a new file. So that accidentally existing file is not overwritten of truncated.
  • (‘a’ ) –  Append mode, opens a new file, if it does not exist. Else added the new content to the end of the file without altering file contents.
  • (‘t’ ) –  Text mode (default)
  • (‘b’ ) –  Binary mode
  • (‘+’ ) –   Open a file for read and write mode.

Exception- If open fails, throws an exception, FileNotFoundError.

Open a file with no access mode.

# opens myFile.text file at current folder
try:
fileName = "myFile.txt";
fileObj = open(fileName);

except FileNotFoundError: 
print("Failed to open file: ",fileName, "No such file");
else:
print("File is opened successfully",fileObj);

Output:

\Python Examples>py fileHandling.py
Failed to open file: myFile.txt No such file

There is an exception because the python code opens the file in read mode and there is no such file in the current directory.  Let’s change the code to open in write mode.

# opens myFile.text file at current folder in write mode
try:
fileName = "myFile.txt";
fileObj = open(fileName,'w');

except FileNotFoundError: 
print("Failed to open file: ",fileName, "No such file");
else:
print("File is opened successfully",fileObj);

Output:

\Python Examples>py fileHandling.py
File is opened successfully <_io.TextIOWrapper name='myFile.txt' mode='w' encoding='cp1252'>

The file is opened, you can also check in the directory, there is a new empty file with the name myFile.txt.

Writing contents to the file(new or existing):

# opens myFile.text file at current folder in write mode
try:
fileName = "myFile.txt";
fileObj = open(fileName,'w');
fileObj.write("Name : CsPsProtocol");
fileObj.write('\n'); #new line
fileObj.write("Article : Learn file handling in python");

except FileNotFoundError: 
print("Failed to open file: ",fileName, "No such file");
else:
print("Written in file : ",fileName);

Output:

On Console :

Python Examples>py fileHandling.py
Written in file : myFile.txt

The content of the file is :

Name : CsPsProtocol
Article : Learn file handling in python

How to read a file?

Open a file and call the read(size) function on the file object.  It will read the number of specified bytes in size. If read reaches the EOF, it returns. If no size specified, read the complete file.

# Reads myFile.text file at current folder
try:
fileName = "myFile.txt";
fileObj = open(fileName,'r');
readText = fileObj.read();

except FileNotFoundError: 
print("Failed to open file: ",fileName, "No such file");
else:
print("File contents : ",readText);

Output:

Python Examples>py fileHandling.py
File contents : Name : CsPsProtocol
Article : Learn file handling in python

Here is a code example that mentions , various options to read.

# Reads myFile.text file at current folder
try:
fileName = "myFile.txt";
fileObj = open(fileName,'r');
readText = fileObj.read(6);
print("Read 6 characters from start of file : ",readText);
readText = fileObj.read(6);
print("Read 6 characters after 6 characters read : ",readText);
readText = fileObj.seek(0); # Move to start of file
readText = fileObj.read(); 
print("Read From start : ",readText);
readText = fileObj.read();
print("Read After Full read (Empty) : ",readText);

readText = fileObj.seek(10); #Move to 10 position 
readText = fileObj.read();

print("Read from 10th position. : ",readText);
except FileNotFoundError: 
print("Failed to open file: ",fileName, "No such file");
else:
print("Success");

Output:

Python Examples>py fileHandling.py
Read 6 characters from start of file : Name :
Read 6 characters after 6 characters read : CsPsP
Read From start : Name : CsPsProtocol
Article : Learn file handling in python
Read After Full read (Empty) :
Read from 10th position. : sProtocol
Article : Learn file handling in python
Success

How to append (modify) text to a file?

# Append in file myFile.text example
try:
fileName = "myFile.txt";
fileObj = open(fileName,'r');
readText = fileObj.read();
print("Original Content : ",readText);

fileObj.close();
fileObj = open(fileName,'a');
fileObj.write('\n');
fileObj.write("New Content appended");
fileObj.close();
fileObj = open(fileName,'r');

readText = fileObj.read();
print("After Append : ",readText);

except FileNotFoundError: 
print("Failed to open file: ",fileName, "No such file");
else:
print("Success");

Output:

\Python Examples>py fileHandling.py
Original Content : Name : CsPsProtocol
Article : Learn file handling in python
After Append : Name : CsPsProtocol
Article : Learn file handling in python
New Content appended
Success

How Close a file?

The method close(), closes the file. It will not have any impact if the file is already closed.