Skip to content

File system

File system operations

Test

Action Code Details
File/dir exists
os.path.exists(path)
Is file
os.path.isfile(path)
Is empty file
os.path.getsize(path) == 0
Throws error if the file does not exist
Is directory
os.path.isdir(path)
Is empty directory
not os.listdir(path)

File handling

Action Code Details
Open temporary file with clean-up
with tempfile.NamedTemporaryFile() as file:
    path = file.name

File info

Action Code Details
Filename
os.path.basename(r'C:\Files\derp.csv')
Returns 'derp.csv'
Filename without extension
os.path.splitext(os.path.basename(r'C:\Files\derp.csv'))[0]
Returns 'derp'
File extension
os.path.splitext(r'C:\Files\derp.csv')[1]
Returns '.csv'
Parent directory name
os.path.basename(os.path.dirname((r'C:\Files\derp.csv'))
Returns 'Files'
File size
os.path.getsize(path)

Directory handling

Action Code Details
Create directory
os.mkdir(path)
Error when directory already exists
Create directory if missing
Path(path).mkdir(exist_ok=True)
Create directories, recursively
os.makedirs(dest_dir)
Create directories recursively if missing
os.makedirs(dest_dir, exist_ok=True)
Rename a directory
?
Delete directory and underlying files
shutil.rmtree(path)
Error if the path does not exist
Delete directory and underlying files, if needed
shutil.rmtree(path, ignore_error = True)

Info

Action Code Details
Number of children
?
Number of files
?
Number of child directories
?