Newby Coder header banner

Python File Handling

Opening and Closing Files

Python provides some basic functions and methods to perform operations on a file

A file object can be used to read and manipulate files

open function - Open a file in Python

To read or write a file, it has to be opened using Python's built-in open() function

This function creates a file object, which can then be utilized to call other methods associated with it

Syntax

file object = open(file_name [, access_mode][, buffering]) 

Here is a list of the different modes of opening a file :

Sr.No Modes Description
1

r

Opens a file for reading only

The file pointer is placed at the beginning of the file, by default

This is the default access mode
2

rb

Opens a file for reading only in binary format

File pointer is placed at the beginning

3

r+

Opens a file for both reading and writing

File pointer is placed at the beginning

4

rb+

Opens a file for both reading and writing in binary format

File pointer is placed at the beginning

5

w

Opens a file for writing only, overwriting any content in the file

If file doesn't exist, it creates a new file

6

wb

Opens a file for writing only in binary format, and overwrites existing file

If the file does not exist, creates a new file

7

w+

Opens a file for both writing and reading, and overwrites existing file

If the file does not exist, it creates a new file

8

wb+

Opens a file for both writing and reading in binary format, and overwrites existing file

If the file does not exist, it creates a new file

9

a

Opens a file for appending at the end of the file

If the file does not exist, it creates a new file

10

ab

Opens a file for appending in binary format and places file pointer at the end of file

If the file does not exist, it creates a new file

11

a+

Opens a file for both appending and reading, and places file pointer at the end of file

If the file does not exist, it creates a new file

12

ab+

Opens a file for both appending and reading in binary format, and places file pointer at the end of file

If the file does not exist, it creates a new file

close() function - Closing a file in Python

close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done

Python automatically closes a file when the reference object of a file is reassigned to another file

It is considered a good practice to use the close() method to close a file

Syntax

fileObject.close(); 

Example

#!/usr/bin/python
# Open a file
fo = open("foo.txt","wb")
print"Name of the file: ", fo.name

# Close opened file
fo.close() 

Output :

Name of the file:  foo.txt 

file Object Attributes

A file object, created by opening a file, contains information related to the file

Sr.No Attribute Description
1

file.closed

Returns true if file is closed

2

file.mode

Returns access mode with which file was opened

3

file.name

Returns name of the file

4

file.softspace

Returns false if space explicitly required with print, true otherwise

Example

#!/usr/bin/python
# Open a file
fo = open("foo.txt","wb")
print("Name of the file: ", fo.name)
print("Closed or not : ", fo.closed)
print("Opening mode : ", fo.mode)
print("Softspace flag : ", fo.softspace) 

Output :

Name of the file:  foo.txt
Closed or not :  False
Opening mode :  wb
Softspace flag :  0 

Reading and Writing Files

The file object provides a set of access methods to make our lives easier

We would see how to use read() and write() methods to read and write files

write() function - Write in a file using Python

The write() method writes any string to an open file

Python strings can have binary data, apart from text data
write() method does not add a newline character ('\n') to the end of the string

Syntax

fileObject.write(string); 

Here, passed parameter is the content to be written into the opened file

Example

#!/usr/bin/python
# Open a file
fo = open("foo.txt","wb")
fo.write("Sometimes people cross lines \n Sometimes people don't\n")
# Close opened file
fo.close() 

The above method would create foo.txt file and would write given content in that file and finally it would close that file

If you would open this file, it would have following content

Python is a great language.
Yeah its great!! 

read() function - Read a file using Python

The read() method reads a string from an open file

Syntax

fileObject.read([count]); 

Here, passed parameter is the number of bytes to be read from the opened file

This method starts reading from the beginning of the file and if count is missing, then it tries to read until the end of file

Example

Consider file foo.txt, assuming it is created as mentioned above

#!/usr/bin/python
# Open a file
fo = open("foo.txt","r+")
str = fo.read(10);
print"String read from file : ", str
# Close opend file
fo.close() 

This produces following output:

String read from file : Sometimes people cross lines 

File Positions

tell() method returns the current position in terms of bytes, within the file; in other words, the next read or write occurs at that many bytes from the beginning of the file

seek(offset[, from]) method changes the current file position

If from is set to 0, it uses the beginning of the file as the reference position and 1 uses the current position as the reference position and if it is set to 2 then the end of the file is taken as the reference position

Example

Consider file foo.txt, as mentioned above

#!/usr/bin/python
# Open a file
fo = open("foo.txt","r+")
str = fo.read(10);
print("String read from file : ", str)

# Check current position
position = fo.tell();
print("Current file position : ", position)

# Reposition pointer to the beginning
position = fo.seek(0,0);
str = fo.read(10);
print("String read from file after seek() : ", str)

# Close opened file
fo.close() 

Output :

String read from file : Sometimes people cross lines
Current file position :  10
String read from file after seek() : Sometimes people cross lines 

Renaming and Deleting Files

Python os module provides methods that help to perform file-processing operations, such as renaming and deleting files

To use this module it has to be imported like -

import os 

rename() function - Rename a file using Python

The rename() method takes two arguments, the current filename and the new filename

Syntax

os.rename(current_file_name, new_file_name) 

Example

Example to rename an existing file test1.txt:

#!/usr/bin/python
import os

# Rename a file from file1.txt to filename2.txt
os.rename("file1.txt","filename2.txt") 

remove() function - Remove a file using Python

The remove() method is used to delete files by supplying the name of the file as the argument

Syntax

os.remove(file_name) 

Example

Example to delete an existing file file2.txt :

#!/usr/bin/python
import os

# Delete file file2.txt
os.remove("file2.txt") 

Directories in Python

Python has inbuilt functions to handle operations involving directories

The os module has methods to create, remove, and change directories

mkdir() function - Create directory using Python

The mkdir() method of the os module is used to create directories in the current directory

It accepts the name of the directory to be created as argument

Syntax

os.mkdir("newdir") 

Example

Example to create a directory Newfolder in the current directory :

#!/usr/bin/python
import os

# Create a directory "Newfolder"
os.mkdir("Newfolder") 

getcwd() function - Get current directory using Python

The getcwd() method displays the current working directory

Syntax

os.getcwd() 

Example

Example to get current directory :

#!/usr/bin/python
import os

# This returns location of the current directory
os.getcwd() 

chdir() function - Change directory using Python

The chdir() method can be used to change the current directory

It takes as argument, the name of the directory that is to be made the current directory

Syntax

os.chdir("new_dir_path_or_name") 

Example

Example to go to "/home/somedir" directory :

#!/usr/bin/python
import os

# Changing directory to "/home/somedir"
os.chdir("/home/somedir") 

rmdir() function - Delete directory using Python

rmdir() method deletes the directory, which is passed as an argument to the method

Before removing a directory, all the contents in it should be removed

Syntax

os.rmdir('dirname') 

Example

Example to remove "/tmp/test" directory

#!/usr/bin/python
import os

# This would  remove "/tmp/test"  directory.
os.rmdir("/tmp/test") 
If fully qualified name of the directory is not provided, then it searches for that directory in current directory
It is recommended to use any of the functions mentioned above inside a try-except block