File input-output (I/O) and file handling in Python.
A file in a computer is a piece of persistent information stored in the secondary memory(e.g., A Hard Disk Drive). It can be in binary or plain text format. The operating system provides text editors to create, delete, or edit files.
This tutorial will describe how to perform input/output operations on a file using Python scripts programmatically.
File input/output and standard I/O.
The terms file input and file output are used in Python to refer to reading the contents of a file into a program and writing data to the same or another file. The previous tutorial for Python I/O explained how a program could perform standard input and output using library functions print()
and input()
.
In contrast to standard I/O, file input/output does not read and write values from or to a standard keyboard and console. A programmer may remain away from the console with file-based I/O, while in another case, he must be present and enter values from the keyboard as well as note values from the screen.
File handling based I/O is most commonly seen in application logs. Application logs are written to a file when the application executes, and another program can read the logs to generate error alarms.
What functions does Python provide for handling files?
- Create a new file or open an existing one.
- Reading from a file.
- Writing to a file.
- Modify a file.
- Close an opened file.
How to create or open a file?
Prototype – Object open(fileName(M), accessMode(O)); Here M- Mandatory, O-Optional
To open a file, Python provides the open() function. The function accepts two arguments and returns an object for the file. The first argument is the file name, and the second is the access mode.
With the return object, it is possible to perform operations (such as reading, writing, etc.) on an opened file. AccessMode is an optional parameter. Without this option, the file will be opened in read mode only.
Python has the following file access modes:
('r' )
– Read mode (default), open fails if the file does not exist.('w' )
– Write mode, open a new file if it does not exist. Else remove all contents of the existing file.('x' )
– Exclusive creation, Fails if a file exists. Useful when you always want to open a new file. So that the accidentally existing file is not overwritten or 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.
# The program opens a file named myFile.text located in the current directory.
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 a 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'>
Once the file is opened, you can also verify the same in the directory. There is a new empty file with the name myFile.txt.
Writing contents to the file(new or existing):
# The program opens file name myFile.text in current folder for writing
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 as follows:
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 the reader reaches the EOF, it returns. If no size is 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 to close an already open file?
The method close(),
closes the file. It will not have any impact if the file is already closed.