Python File Handling

Python File handling is an important part of any web application. It is nothing but, the operating system uses the filehandle internally when accessing the file. It is a special area of main memory that is reserved for file handling, and the size of the area determines how many files can be open at once.

Python File Handling

Python has several functions for creating, reading, updating and deleting files.

Methods for Opening File in Python

There are 4 methods for opening files. open( ) function has two parameters i.e filename and mode.

Modes Function Description
  “r” Read Opens a file for reading, and shows an error if the file doesn’t exist
“a” Append Opens a file for appending, creates if a file doesn’t exist
  “w” Write Opens a file for writing, creates if the file doesn’t exist
“x”  Create Creates a specified file and returns an error if the files exist
“t” text It gives default values, in text mode
“b” Binary binary mode (ex: images)

Syntax

To open a file for reading it is:
f = open(“demofile.txt”)
The above syntax is same as : f = open(“demofile.txt”, “rt”)
Here, “r” & “t” are default values, you do not need to specify them.

Reading & Writing Files in Python

The file object provides a set of access methods for accessing the files easier.

Read( ) method

It reads a string from an open file. Remember that Python strings have binary data, apart from text data.

Syntax: fileObject.read([count]);

Example

# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "FreshersnowString is : ",str# 
Close opened filefo.close()

Output: Read String is: Freshersnow is

Write( ) Method

It writes any string to open files. Remember that Python strings have binary data, but not only text.
Syntax: fileObject.write(string);

Example

# Open a filefo = open("foo.txt", "wb")
fo.write( "Freshersnow is awesome.\nHey Freshersnow!!\n");
#Close opend filefo.close()

Output
Freshersnow is awesome.
Hey Freshersnow

Read Lines( )

We can read the lines by using the readline( ) method.

Example

f = open("demofile.txt", "r")
print(f.readline())

Output: Hello! Welcome to demofile.txt

Renaming & Deleting files in Python

By using python file handling commands or methods we can also delete and rename the files.

rename( ) method

It will be taking two arguments. i.e current file name & new file name.

 Syntax: os.rename(current_file_name, new_file_name)

Example

import 
osos.rename( "test1.txt", "test2.txt" )

remove( ) method

we can use the remove( ) method to delete files.
 Syntax: os.remove(file_name)

Example

import 
osos.remove("text2.txt")

Directories in Python

All the python file handling is stored at different directories. They are as follows:

mkdir( ) method

It helps you to create files in the new directory.
 Syntax: ab.mkdir(“newdir”)

Example

import os
ab.mkdir("test")

chdir( ) method

You can use this method to change the directory.

Syntax: ab.chdir(“newdir”)

Example

import os
os.chdir("/home/newdir")

getcwd( ) method

It displays the current working directory.
 Syntax: os.getcwd()

Example

import os
os.getcwd()

rmdir( ) method

It deletes the directory which is passed through an argument in methods. Before removing the directory all the content should be removed.
Syntax: os.rmdir(‘dirname’)

Example

import 
osos.rmdir( "/tmp/test" )

Close files

After finishing the task try to close the files.

Example

f = open("demofile.txt", "r")
print(f.readline( ))
f.close( )

Output: Hello! Welcome to demofile.txt