Python File Handler- Create, Read, Write, Access, Lock File
File handling is an important part of the development process. Like other programming languages, Python also provides 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.
Python create a file
Python provides the 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 the file already exists,
t (text)- opens a file in text mode,
b (binary)- opens a file in binary mode, like to handle images.
Python open a file
Python provides the 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 an error if the specified file already 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'
Python write to a file
Python provides the write() method to write on a file, but the file should be opened first in either write (w) or append (a) mode.
f = open("test.txt", "w")
f.write("Write your text here")
f.close()
Python read a file
Python provides the 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
Python delete a file
The remove() method deletes the specified file. This method needs to import the 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 as a 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 to have 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 been installed, you can import this to lock the file. Here is an example of how 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 from accessing the file while updating. In this example below, we first lock the file and then append the text to 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 ConnectorPython file handling programs
Find the stop words in nltk Python
Python program to count the occurrences of a word in a text file
How to read data from excel file in Python
Read data from excel file using Python Pandas
Convert Excel to CSV Python Pandas
How to read and write a file using Django
Python write to csv file
Convert MySQL query result to JSON in Python
Fibonacci 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