Python File Handler - Create, Read, Write, Access, Lock File
File handling is the important part in the development process. Like other programming languages, python also provide methods for file handling. In this article, you will learn to create, access, read and write files and also learn the most important file locking system.
Create a File
Python provides open() function to create a file. This is the key function to create, open, read and write a file.
Syntax of open()
open(filename, mode)
filename - the name of file.
mode - purpose of opening the file, like read, write, append.
These are the different modes of opening a file -
r (read) - Opens a file for reading purpose,
w (write) - Opens a file for writing purpose,
a (append) - Opens a file for appending text,
x (create) - Creates a file and returns true if file already exists,
t (text) - Opens a file in text mode,
b (binary) - Opens a file in binary mode, like to handle images.
Open a file
Python provides open() method to create a file. It accepts two parameters - filename and modes.
open(filename, mode)
Here, the mode should be -
a (append) - Creates a file, if the specified file does not exist,
w (write) - Creates a file, if the specified file does not exist,
x (create) - Creates a file and returns error, if the specified file exists.
Example - opening a file
open("test.txt", "xt")
print("File created successfully")
In the above example, if the "test.txt" file already exists, then it returns the following errors -
Traceback (most recent call last):
File "C:\Python38\Scripts\createfile.py", line 1, in
open("test.txt", "xt")
FileExistsError: [Errno 17] File exists: 'test.txt'
Write to a file
Python provides write() method to write on a file but the file should be open first in write (w) or append (a) mode.
f = open("test.txt", "w")
f.write("Write your text here")
f.close()
Read a file
Python provides read() method to read an existing file.
f = open("test.txt", "r")
print(f.read())
The above code returns the following -
Write your text here
Delete a file
The remove() method deletes the specified file. This method needs to import Python in built OS module.
import os
os.remove("test.txt")
Python File methods
These are the lists of file methods -
Method | Description |
---|---|
close() | closes the open file |
fileno() | In the perspective of the operating system, it returns the stream in number. |
flush() | It releases the internal buffer. |
read() | It returns the file content. |
readline() | It returns the oneline from the file content. |
readlines() | It returns the list of lines from the file content. |
truncate() | It resizes the file to the specified size. |
write() | It writes the content on the file. |
writable() | It checks whether the file can be written or not. |
Python FileLock
To lock a file, we need to install a lockfile module. This is a platform independent file locking package.
Python provides the PIP package manager to manage software packages. So, we need PIP installed on the system first. The latest version of Python comes with PIP pre installed.
Here is the command to install the LockFile module -
pip install lockfile
Once this has installed, you can import this for locking file. Here is the example to lock a file.
from lockfile import LockFile
lock = LockFile("E:/dbbkup/demo.txt")
with lock:
print (lock.path, ' is locked.')
The file locking system is also important where there is need to update the file text. This prevents others to access the file while updating. In this example below, we first lock the file and then append the text in it.
from lockfile import LockFile
filePath = "C:/Python38/Scripts/hello.txt"
lockPath = "C:/Python38/Scripts/hello.txt.lock"
lock = LockFile(lockPath)
with lock:
open(filePath, "a").write("Hello John")
print("Text appended")
lock.acquire()
print("File is locked")
Related Articles
CRUD operations in Python using MYSQL ConnectorFibonacci Series Program in Python
Python convert XML to JSON
Python convert xml to dict
Python convert dict to xml
How to generate QR Code in Python using PyQRCode
Python programs to check Palindrome strings and numbers