在Python中,你可以使用os
模块来处理文件和目录路径。以下是一些常用的操作:
import os
current_directory = os.getcwd()
print(current_directory)
import os
new_directory = "new_folder"
os.mkdir(new_directory) # 如果目录已存在,会抛出FileExistsError异常
import os
path = "parent/child/subchild"
os.makedirs(path, exist_ok=True) # exist_ok=True表示如果父目录不存在也允许创建
import os
directory = "my_directory"
files = os.listdir(directory)
print(files)
import os
path = "my_directory"
if os.path.exists(path):
print("Path exists")
else:
print("Path does not exist")
import os
filename = "example.txt"
file_extension = os.path.splitext(filename)[1]
print(file_extension) # 输出:.txt
import os
base_path = "parent/child"
file_name = "example.txt"
full_path = os.path.join(base_path, file_name)
print(full_path) # 输出:parent/child/example.txt
import os
filename = "example.txt"
new_extension = ".bak"
new_filename = os.path.splitext(filename)[0] + new_extension
print(new_filename) # 输出:example.bak
这些只是os
模块中关于路径处理的一些基本操作。你可以根据需要进行更多的操作。