在Python中,可以使用os
和os.path
模块来处理和转换路径。以下是一些常用的方法:
import os
current_directory = os.getcwd()
print(current_directory)
import os
relative_path = "example.txt"
absolute_path = os.path.abspath(relative_path)
print(absolute_path)
import os
absolute_path = "/home/user/documents/example.txt"
relative_path = os.path.relpath(absolute_path)
print(relative_path)
import os
path = "/home/user/documents/example.txt"
filename = os.path.basename(path)
directory = os.path.dirname(path)
print(filename)
print(directory)
import os
path = "/home/user/documents/example.txt"
if os.path.exists(path):
print("Path exists")
else:
print("Path does not exist")
import os
directory = "new_directory"
if not os.path.exists(directory):
os.makedirs(directory)
import os
path = "/home/user/documents"
for root, dirs, files in os.walk(path):
for directory in dirs:
print(os.path.join(root, directory))
for file in files:
print(os.path.join(root, file))
这些方法可以帮助你在Python中处理和转换路径。根据实际需求,你可以选择合适的方法来实现路径操作。