Now that you understand the basics of file paths in Python, let's explore how to handle file operations in a cross-platform manner.
Reading and Writing Files
The open()
function in Python is used to open files, and it can be used with both absolute and relative paths. When opening a file, you should use the appropriate file mode, such as 'r'
for reading, 'w'
for writing, or 'a'
for appending.
import os
## Open a file using an absolute path
absolute_path = os.path.join("/", "home", "user", "documents", "file.txt")
with open(absolute_path, 'r') as file:
content = file.read()
print(f"File content: {content}")
## Open a file using a relative path
relative_path = os.path.join("documents", "file.txt")
with open(relative_path, 'w') as file:
file.write("This is a cross-platform file.")
Creating and Deleting Files and Directories
The os
module provides functions to create and delete files and directories in a cross-platform way.
import os
## Create a directory
directory_path = os.path.join("/", "home", "user", "new_directory")
os.makedirs(directory_path, exist_ok=True)
## Create a file
file_path = os.path.join(directory_path, "new_file.txt")
with open(file_path, 'w') as file:
file.write("This is a new file.")
## Delete a file
os.remove(file_path)
## Delete a directory
os.rmdir(directory_path)
Handling File and Directory Existence
You can use the os.path.exists()
function to check if a file or directory exists, and the os.path.isfile()
and os.path.isdir()
functions to determine if a path refers to a file or a directory, respectively.
import os
## Check if a file exists
file_path = os.path.join("/", "home", "user", "documents", "file.txt")
if os.path.exists(file_path):
print(f"File '{file_path}' exists.")
else:
print(f"File '{file_path}' does not exist.")
## Check if a directory exists
directory_path = os.path.join("/", "home", "user", "documents")
if os.path.isdir(directory_path):
print(f"Directory '{directory_path}' exists.")
else:
print(f"Directory '{directory_path}' does not exist.")
By using the functions and techniques covered in this section, you can write Python code that handles file operations in a cross-platform manner, ensuring your application works consistently across different operating systems.