Files organization
Table of contents
The sys and os modules can also be useful for this purpose, so check out a tutorial about them here.
The pathlib module
The pathlib module provides an object-oriented interface for handling filesystem paths.
from pathlib import Path
import os
p = Path("folder/file.txt") # creating a Path object
print(p.name) # displaying the file name
print(p.stem) # displaying the file name without extension
print(p.suffix) # displaying the file extension
print(p.parent) # displaying the parent directory
print(p.anchor) # displaying the root or drive
print(p.parts[0]) # displaying the first part of the path
print(p.parts[1]) # displaying the second part of the path
print(Path.cwd()) # displaying the current working directory
print(Path.home()) # displaying the home directory
print(p.absolute()) # displaying the absolute path
print(os.path.abspath("file.txt")) # converting a path to an absolute path
print(os.path.isabs("file.txt")) # checking whether the path is absolute
print(os.path.relpath("/home/user/file.txt", "/home")) # calculating the relative path
print(os.path.getsize("file.txt")) # displaying the file size
print(os.path.dirname("/home/user/file.txt")) # displaying the directory name
for file in Path(".").glob("*.txt"):
print(file) # displaying all TXT files
The shutil module
The shutil module allows us to copy and move files and folders.
import shutil
from pathlib import Path
p = Path("file.txt") # creating a path object
shutil.copy("file.txt", "copy.txt") # copying a file
shutil.move("copy.txt", "folder/copy.txt") # moving a file
shutil.copytree("folder", "folderCopy") # copying a whole directory
p.unlink() # deleting a file
The send2trash module
The send2trash module allows us to move files to the trash can instead of permanently deleting them.
from send2trash import send2trash
send2trash("file.txt")
The zipfile module
The zipfile module is used to handle files with the .zip extension, i.e. compressed folders.
Write the import zipfile statement at the beginning of every example.
Zipping files
z = zipfile.ZipFile("myZip.zip", "w")
z.write("file.txt")
z.write("file2.txt")
z.close()
namelist()
# Checking the contents of a zip file (a list of files)
z = zipfile.ZipFile("myZip.zip", "r")
print(z.namelist())
z.close()
Unzipping files
There are two ways of unzipping files.
z = zipfile.ZipFile("myZip.zip", "r")
for x in z.namelist():
z.extract(x)
z.close()
z = zipfile.ZipFile("myZip.zip", "r")
z.extractall()
z.close()