Python File Operations :
Python file operation is similar to unix file operations. python uses os.path module functions and also uses functions from newer pathlib module.
Methods of File Task :
- exists() – To check whether file exists or not. Also check with relative or absolute pathname.
import os
os.path.exists('Binary.txt')
#Output
False
import os
os.path.exists('.') #Single dot(.) represents current directory.
# Output
True
import os
os.path.exists('..') #Double dot(.) represents parent directory.
#Output
True
2. copy( ) method using shutil module
copy method used to copy one file to another file.
file = open('abc.txt','wt')
file.write('Python programming')
#Output
18
import shutil
shutil.copy('abc.txt','def.txt')
#Output
'def.txt'
3. isdir( ) – Determine a directory
os.path.isdir('ABC')
#output
False
4. rename() – method used to Rename a file.
import os
os.rename('abc.txt','def.txt')
5. remove() – method Deletes a file.
import os
os.remove('ABC.txt') # Remove the file
os.path.exists('ABC.txt') #Check with either file exist now.
#Output
False
Operations on Directory
Folder in windows are directory.
- mkdir() – make a directory
os.mkdir('root')
os.path.exists('root')
#Output
True
2. rmdir() – To delete a Directory
os.rmdir('root')
os.path.exists('root')
#Output
False
3. listdir() – To get a list of contents in a directory.
import os
os.listdir('root')
#Output
[] # Blank for now- no content
4. Creating a Subdirectory using mkdir()
import os
os.mkdir('Directory/SubDirectory')
os.path.exists('Directory/SubDirectory') #This works only if Directory already closed.
#Output
True
5. Again applying listdir() to get the content.
import os
os.listdir('Directory')
# Output
['SubDirectory']
6 Write MyStory in the directory with content
Mystory = 'Ankit Effortless python tutorials'
fileobject = open('Directory/SubDirectory/Story_of_Python', 'wt')
fileobject.write(Mystory)
fileobject.close()
#Lets see the list again with what content we have.
os.listdir('Directory/SubDirectory')
Output
['Story_of_Python']
7. os.getcwd() – To Get current directory
import os
os.getcwd()
# 'C:\\Users\\Moshu'
8. chgdir() – Chnage current directory
Remember – python uses 2 slashes in place of 1 slash as compare to Windows and Unix.
import os
#Change directory to below one
os.chdir('C:\\Users\\Moshu\\Directory\\SubDirectory')
#See the current directory now
os.getcwd()
Output
'C:\\Users\\Moshu\\Directory\\SubDirectory'
9. glob() method of glob module – List matching use wild cards.
globe function matches the file names.
Follow the rules below.
- ? Matches single character.
- [XYZ] Matches X, Y, Z.
- [!XYZ] Matches except X, Y, Z.
- * Matches everything.
Examples of glob() method.
For the file ‘C:\Users\Moshu\Directory\Story_of_Python’
# Any two letter file or directory
import glob
glob.glob('??')
# Output
[]
# Starts with S, A or M and ends with y
import glob
glob.glob('[SAM]*n')
#output
['Story_of_Python']
# Starts with S and ends with anything
import glob
glob.glob('S*')
#output
['Story_of_Python']
Pathname in Python
When you are referring to a filename or a directory, you must have its pathname.
It must be an absolute path from top to bottom or a relative path to your current directory.
‘C:\\Users\\Moshu\\Directory\\Story_of_Python‘
Note : Python allows only two backslash \\ in a path above, because single \ represents an escape character in python.
How to get a pathname with abspath()
In below example, we gets the absolute path (top to bottom) out of relative path in current directory.
import os
os.path.abspath('Story_of_Python.txt')
#outpt
'C:\\Users\\Moshu\\Directory\\SubDirectory\\Story_of_Python.txt'
Create a path name with os.pth.join() method
import os
file = os.path.join("Root","Base")
file = os.path.join(file,"File.txt")
print(file)
#Output
Root\Base\File.txt
pathlib() method Alternative to os.path module
Python introduces Pathlib module from 3.4 onwards, It is an alternative os.path module.
The Slash trick often taking advantage of python Magic Methods and a path is self explainatory.
from pathlib import Path
file = Path('Root') / 'Base' / 'File.txt'
print(file)
#Output
Root\Base\File.txt
Self Explanatory filenames with pathlib
file.stem
#output
'File'
file.suffix
#Output
'.txt'
1 thought on “Python File Operations”