6.1 Working with Files
Python gives us tons of built-in functions and modules to deal with files and directories. The main operations are done using built-in modules like os
, shutil
, and others.
Three main file operations:
- Copying
- Moving
- Deleting
The shutil
module is perfect for doing these operations.
Copying a file
import shutil
shutil.copy('source.txt', 'destination.txt')
Moving a file
import shutil
shutil.move('source.txt', 'destination.txt')
Deleting a file
import os
os.remove('example.txt')
Couldn't be simpler.
6.2 Checking File Existence
We often need to check if a specific file exists or not. The os
module has a special method for this — exists()
.
Checking if a file exists
import os
if os.path.exists('example.txt'):
print("File exists")
else:
print("File does not exist")
# If the file doesn't exist, the program will execute the actions described in the else block.
# For example, you might want to display a warning, create a new file, or exit the program.
If the file doesn't exist, the program can handle it with conditions or throw an exception.
6.3 Checking if an Object is a File or Directory
We often need to check if an object is a file or a directory. For example, if you are reading all the contents of a directory and need to handle files one way and directories another.
For these cases, there are two special methods — isdir()
, which checks if an object is a directory, and isfile()
, which checks if it's a file.
Checking if it's a directory
if os.path.isdir('example_directory'):
print("It's a directory")
else:
print("It's not a directory")
Checking if it's a file
if os.path.isfile('example_file'):
print("It's a file")
else:
print("It's not a file")
These are super useful functions that you'll use more than you think. :)
6.4 Working with Paths
The os
module has a sub-module called os.path
, which has useful functions for dealing with files and directories. Here are some of them:
Getting a File Extension
The splitext()
function splits the filename into two parts and returns a list with two elements: the name and the extension.
import os.path
# Getting a file extension
file_path = 'example.txt'
file_extension = os.path.splitext(file_path)[1]
print(f"File extension: {file_extension}")
Getting a filename without extension
import os.path
# Getting a filename without extension
file_path = 'example.txt'
file_name = os.path.splitext(os.path.basename(file_path))[0]
print(f"Filename without extension: {file_name}")
Getting a filename from a path
The basename()
function returns just the filename, cutting off the entire path to it.
import os.path
# Getting a filename from a path
file_path = '/path/to/example.txt'
file_name = os.path.basename(file_path)
print(f"File name: {file_name}")
Getting a directory from a path
It's also easy to get just the directory from the filename using the dirname()
function.
import os.path
# Getting a directory from a path
file_path = '/path/to/example.txt'
directory = os.path.dirname(file_path)
print(f"Directory: {directory}")
Joining Paths
If you have a separate directory and a separate filename, you can get the full path to that file.
import os.path
# Joining paths
directory = '/path/to'
file_name = 'example.txt'
full_path = os.path.join(directory, file_name)
print(f"Full path: {full_path}")
6.5 Platform-Independent Paths
When working with paths, it's important to consider the differences between operating systems. Path separators can differ, and code that works on one platform might not work on another. To avoid issues when transferring code between different operating systems, use functions like os.path.join()
, os.path.abspath()
, and os.path.dirname()
, which ensure compatibility across platforms.
For example:
import os
# Joining paths in a platform-independent way
directory = 'some_directory'
file_name = 'example.txt'
full_path = os.path.join(directory, file_name)
print(f"Full path: {full_path}")
Getting the Absolute Path
If you have a path relative to your current working directory but want to convert it to an absolute one, there's the abspath()
function.
import os.path
# Getting the absolute path
relative_path = 'example.txt'
absolute_path = os.path.abspath(relative_path)
print(f"Absolute path: {absolute_path}")
Important!
Always use system functions when dealing with paths, as your code may run on another operating system where the file separator might not be \
but /
, or where ":"
is restricted in paths, or other such differences.
GO TO FULL VERSION