File handling is the process of storing, reading, and writing data to and from files permanently on a storage device, rather than just in a computer's memory.
In this tutorial, you are going to learn the following,
- Types of files that can be handled in Python.
- The modes of opening a file.
- Reading from a file.
- Writing to a file.
- Using
tell()
andseek()
functions.
Types of data files:
-
Text Files: Stores data in the same format as typed.
- Regular Text Files (.txt)
-
Delimited Text File.
- Tab-Separated Values files (.txt or .csv)
- Comma-Separated Values files (.csv)
- Binary Files: Stores information in the form of a stream of bytes. Not a human-readable format.
Opening and Closing files in Python
fileObj = open("myfile.txt", mode="r")
fileObj.close()
# -------------------------- OR ---------------------------
with open("myfile.txt", mode="r") as fileObj:
data = fileObj.read()
# Closes file automatically once you get out of this indentation
When using filenames with path, you remember the following:
- Always make the file path string a raw string. Using a raw string helps us in ensuring there is no special meaning attached to any character of our file path string.
fileObj = open(r"C:\Temp\data1.txt", mode="r") # Use prefix 'r'
# -------------------------- OR ---------------------------
fileObj = open("C:\\Temp\\data1.txt", mode="r") # Or use double slashes
Common modes of opening a file:
A file-mode governs the type of operations possible in the opened file.
Text File Mode | Binary File Mode | Description |
---|---|---|
'r' | 'rb' | READ ONLY. File must exist already, or Python raises I/O error. |
'w' | 'wb' | WRITE ONLY. File is created if it does not already exist. If the file already exists with data, Python overwrites it. |
'a' | 'ab' | APPEND. File is created if it does not already exist. If the file exists with data, Python retains the data, and new data will be appended to the end. |
'r+' | 'rb+' or 'r+b' | READ AND WRITE. Properties of READ ONLY mode are applied. Both read and write operations can take place. |
'w+' | 'wb+' or 'w+b' | WRITE AND READ Properties of WRITE ONLY mode are applied. Both read and write operations can take place. |
'a+' | 'ab+' or 'a+b | APPEND AND READ File must exist already, or Python raises I/O error. |
Reading and Writing files in Python
Writing Text files:
write(str)
method -> Writes a string of characters
fileObj.write("Hello World")
writelines([str])
method -> Writes a list of lines.
fileObj.writelines(["Hello 1", "World here"])
Reading Text files:
-
read(n)
method -> Returns a Python String
data = fileObj.read()
# -------------------------- OR ---------------------------
data = fileObj.read(n) # where n is the number of bytes to read.
-
readline(n)
method -> Returns a line of string ending with '\n'
data = fileObj.readline()
# -------------------------- OR ---------------------------
data = fileObj.readline(n) # where n is the number of lines to read.
-
readlines()
method -> Returns a list of lines.
data = fileObj.readlines()
# -------------------------- OR ---------------------------
data = fileObj.readlines()
Reading CSV files:
Opening CSV files with newline=""
ensures that no translation of EndOfLine(EOL) character takes place.
import csv
fileObj = open("data.csv", mode="r", newline="")
cReader = csv.reader(fileObj)
for val in cReader:
print(val)
Writing CSV files:
import csv
fileObj = open("data.csv", mode="w", newline="")
cWriter = csv.writer(fileObj)
cWriter.writerow(["Roll No", "Name", "Marks"]) # Writes only one row
# Writes multiple rows at once.
cWriter.writerows(
[
["01", "Raj", "50"],
["02", "Meera", "46"],
["03", "Anil", "48"],
]
)
fileObj.close()
Writing Binary files:
import pickle
fileObj = open("data.dat", "wb")
data = {"Roll No": 1, "Name": "John", "Marks": 50}
pickle.dump(data, fileObj)
fileObj.close()
Reading Binary files:
import pickle
fileObj = open("data.dat", "rb")
try:
while True:
data = pickle.load(fileObj)
print(data)
except EOFError:
fileObj.close()
The tell()
function
Returns the current position of the file pointer in the file.
pos = fileObj.tell()
The seek()
function
Changes the position of the file-pointer by placing the file-pointer at the specified position of the opened file.
fileObj.seek(offset, mode)
mode can be 0, 1, or 2.
- 0 -> Move the file-pointer with respect to the beginning of the file. (DEFAULT MODE)
- 1 -> Move the file-pointer with respect to the current position of the file.
- 2 -> Move the file-pointer with respect to the end of the file.
seek()
and tell()
functions are mostly used when editing a file.
Top comments (0)