The Python os module has a number of useful file commands that allow developers to perform common file tasks such as changing file permissions, renaming files, or even deleting files. The following snippets are modified examples from Programming Python: Powerful Object-Oriented Programming
os.chmod
os.chmod alters a file’s permissions. The example usage below takes two arguments. The first argument is the path to the file and the second argument is a 9-bit string that composes the new file permissions.
os.chmod('belchers.txt', 0o777)
os.rename
os.rename is used to give a file a new name. The first argument is the current name of the file and the second argument is the new name of the file.
os.rename('belchers.txt', 'pestos.txt')
os.remove
The os.remove deletes a file. It takes the path of the target file to delete.
os.remove('pestos.txt')
os.path.isdir
The os.path.isdir accepts a path to a file or directory. It returns True if the path is a directory otherwise False.
os.path.isdir('/home') #True os.path.isdir('belchers.txt') #False
os.path.isfile
os.path.isfile works like os.path.isdir but only it’s for files.
os.path.isfile('belchers.txt') #True os.path.isfile('/home') #False
os.path.getsize
os.path.getsize returns the size of the file. It accepts the path to the file as an argument.
os.path.getsize('belchers.txt')
Sources
Lutz, Mark. Programming Python. Beijing, OReilly, 2013.
exactly !
LikeLiked by 1 person