This is a quick reference sheet for working with files and directories using Python. Also, check how to import OS module for working with the operating system.

← GO BACK : Python basics: Functions

var_file = open("filename", "r") #open file for reading
var_file = open("filename", "w") #open file for writing and it is overwritten. If it does not exist, creates a file and opens it for writing.
var_file = open("filename", "r+") #open file for read/write
var_file = open("filename", "rb") #open binary file for reading
var_file = open("filename", "rb+") #open binary file for read/write, with pointer at beginning of file
var_file = open("filename", "wb") #open binary file for writing
var_file = open("filename", "wb+") #open binary file for read/write
var_file = open("filename", "a") #open file for appending
var_file = open("filename", "a+") #open file for read/append
var_file = open("filename", "ab+") #open binary file for read/append
var_file.write( "line1.\nLine2\nLine3") #write to an opened file
var_file.close() #close an opened file

Python has different modules that can be imported and used, such as the ‘math’ module for arithmatic operations and ‘OS’ module for working with operating system and so on.

import os								#import OS module

os.rename(filename, filename_new) #rename a file 
os.path.exists("filename_new") #check if path exists
os.remove(file_name) #delete a file
os.getcwd() #Get current working directory
os.chdir("newdir") #change directory
os.mkdir("newdir") #make new directory
os.system("uname -a") #run shell commands
os.listdir('/home/UnixUtils')                 

In this example Lets check our current directory, create a new one and change to it and try our file operations in it.

 import os
 os.getcwd()

'/home/UnixUtils'

 os.mkdir("testdir1")
 os.chdir("testdir1")
 os.getcwd()

'/home/UnixUtils/testdir1'

 
 os.path.exists("./testfile")

False

 var_f=open("testfile","w")
 var_f.write("This is written with python")
 var_f.close()
 with open("testfile","r") as contents:
     content=contents.read()
 print content

This is written with python

 os.rename('testfile','testfile_new')
 arr = os.listdir('.')
 print arr

['testfile_new']

 
 os.system("ls -l")

 total 4
-rw-rw-r--. 1 unixutils unixutils 27 Dec  2 18:22 testfile_new
0

 os.remove('testfile_new')
 os.system("ls -l")

total 0
0

This site uses Akismet to reduce spam. Learn how your comment data is processed.