File and Directory Paths
File and Directory Paths
Paths
There are two main modules in Python that deal with path manipulation.
One is the os.path module and the other is the pathlib module.
os.path VS pathlib
>>> import os
>>> os.path.join('usr', 'bin', 'spam')
# 'usr\\bin\\spam'
Notice the path separator is different between Windows and Unix based
operating system, that’s why you want to use one of the above methods
instead of adding strings together to join paths together.
Joining paths is helpful if you need to create different file paths under the
same directory.
Using os.path.join on Windows:
Using os on Windows:
>>> import os
>>> os.getcwd()
# 'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
# 'C:\\Windows\\System32'
Using os on Windows:
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
Oh no, we got a nasty error! The reason is that the ‘delicious’ directory does
not exist, so we cannot make the ‘walnut’ and the ‘waffles’ directories
under it. To fix this, do:
There are also the dot (.) and dot-dot (..) folders. These are not real folders,
but special names that can be used in a path. A single period (“dot”) for a
folder name is shorthand for “this directory.” Two periods (“dot-dot”) means
“the parent folder.”
Handling Absolute paths
>>> import os
>>> os.path.isabs('/')
# True
>>> os.path.isabs('..')
# False
You can extract an absolute path with both os.path and pathlib
>>> import os
>>> os.getcwd()'/home/asweigart'
>>> os.path.abspath('..')'/home'
You can get a relative path from a starting path to another path.
>>> import os
>>> os.path.relpath('/etc/passwd', '/')
# 'etc/passwd'
Using pathlib on *nix:
>>> import os
>>> os.path.exists('.')
# True
>>> os.path.exists('setup.py')
# True
>>> os.path.exists('/etc')
# True
>>> os.path.exists('nonexistentfile')
# False
>>> import os
>>> os.path.isfile('setup.py')
# True
>>> os.path.isfile('/home')
# False
>>> os.path.isfile('nonexistentfile')
# False
>>> import os
>>> os.path.isdir('/')
# True
>>> os.path.isdir('setup.py')
# False
>>> os.path.isdir('/spam')
# False
>>> import os
>>> os.path.getsize('C:\\Windows\\System32\\calc.exe')
# 776192
7. Listing directories
>>> import os
>>> os.listdir('C:\\Windows\\System32')
# ['0409', '12520437.cpx', '12520850.cpx', '5U877.ax', 'aaclient.dll',
# --snip--
# 'xwtpdui.dll', 'xwtpw32.dll', 'zh-CN', 'zh-HK', 'zh-TW', 'zipfldr.dll']
WARNING
Directories themselves also have a size! So, you might want to check for
whether a path is a file or directory using the methods in the methods
discussed in the above section.
>>> import os
>>> total_size = 0
>>> for filename in os.listdir('C:\\Windows\\System32'):
total_size = total_size +
os.path.getsize(os.path.join('C:\\Windows\\System32', filename))
.>>> print(total_size)# 1117846456
The shutil module provides functions for copying files, as well as entire
folders.
While shutil.copy() will copy a single file, shutil.copytree() will copy an entire
folder and every folder and file contained in it:
The destination path can also specify a filename. In the following example,
the source file is moved and renamed:
If there is no eggs folder, then move() will rename bacon.txt to a file named
eggs:
>>> import os
>>> for folder_name, subfolders, filenames in os.walk('C:\\delicious'):
print(f'The current folder is {folder_name}')
for subfolder in subfolders:
print('SUBFOLDER OF {folder_name}: {subfolder}')
for filename in filenames:
print('FILE INSIDE {folder_name}: filename{filename}')
print('')
# The current folder is C:\delicious
# SUBFOLDER OF C:\delicious: cats
# SUBFOLDER OF C:\delicious: walnut
# FILE INSIDE C:\delicious: spam.txt