etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

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 -

MethodDescription
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 Connector
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




Most Popular Development Resources
Characteristics of a Good Computer Program
-----------------
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
How to get data from XML file in PHP
-----------------
PHP Create Word Document from HTML
-----------------
How to encrypt password in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP code to send email using SMTP
-----------------
How to get current directory, filename and code line number in PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
PHP MYSQL Advanced Search Feature
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
Simple pagination in PHP with MySQL
-----------------
Fibonacci Series Program in PHP
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
How to add multiple custom markers on google map
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
Php file based authentication
-----------------
PHP Secure User Registration with Login/logout
-----------------
jQuery File upload progress bar with file size validation
-----------------
Polling system using PHP, Ajax and MySql
-----------------
Simple PHP File Cache
-----------------
SQL Injection Prevention Techniques
-----------------
CSS Simple Menu Navigation Bar
-----------------
Simple File Upload Script in PHP
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
PHP User Authentication by IP Address
-----------------
How to generate QR Code in PHP
-----------------
Calculate the distance between two locations using PHP
-----------------
Simple way to send SMTP mail using Node.js
-----------------
Detect Mobile Devices in PHP
-----------------
Set and Get Cookies in PHP
-----------------
PHP Server Side Form Validation
-----------------
To check whether a year is a leap year or not in php
-----------------
Date Timestamp Formats in PHP
-----------------
Get Visitor\'s location and TimeZone
-----------------
Convert MySQL to JSON using PHP
-----------------
Simple Show Hide Menu Navigation
-----------------
PHP Programming Error Types
-----------------
PHP Sending HTML form data to an Email
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
How to print specific part of a web page in javascript
-----------------
Google Street View API Example
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
How to add google map on your website and display address on click marker
-----------------
PHP Getting Document of Remote Address
-----------------
PHP Connection and File Handling on FTP Server
-----------------
File Upload Validation in PHP
-----------------
R Plot Types
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial




General Knowledge

listen
listen
listen
listen
listen
listen
listen
listen
listen


Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 27

    Best AI Startups In India

    Artificial Intelligence is a process of making an intelligent computer machine that does tasks intelligently...

  • Jan 23

    Most in demand programming languages for 2019

    In this article, we have mentioned the analyzed results of the most in demand programming language for 2019...

  • Jan 15

    Web Robots

    Web robots is an internet robot or simply crawlers, or spiders and do not relate this with hardware robots...

  • Jan 12

    Most in demand NoSQL databases software for 2019

    In this article, we have mentioned the analyzed result of most in demand NoSQL database softwares for 2019...

  • Jan 10

    Kotlin : Android App Development Choice

    Kotlin is a general-purpose open-source programming language. It runs on the JVM and its syntax is much like Java...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2021. All Rights Reserved.