Python的os和os.path庫提供了許多函數(shù)來處理文件路徑
import os
current_directory = os.getcwd()
print("當(dāng)前工作目錄:", current_directory)
new_directory = "new_folder"
os.mkdir(new_directory) # 這將在當(dāng)前工作目錄下創(chuàng)建一個名為"new_folder"的新目錄
file_path = "example.txt"
if os.path.exists(file_path):
print("文件或目錄存在")
else:
print("文件或目錄不存在")
file_name = os.path.basename(file_path)
print("文件名:", file_name)
parent_directory = os.path.dirname(file_path)
print("上級目錄:", parent_directory)
combined_path = os.path.join("folder1", "folder2", "file.txt")
print("組合后的路徑:", combined_path)
file_size = os.path.getsize(file_path)
print("文件大小:", file_size, "字節(jié)")
os.rename("old_name.txt", "new_name.txt")
os.remove("file_to_delete.txt") # 刪除文件
os.rmdir("directory_to_delete") # 刪除目錄,注意:目錄必須為空才能刪除
以上只是os和os.path庫中一些常用的函數(shù),更多函數(shù)可以參考官方文檔: