温馨提示×

如何在Python中使用路径

小樊
84
2024-07-17 03:54:51
栏目: 编程语言

在Python中,您可以使用os模块来操作路径。以下是一些常见的路径操作方法:

  1. 获取当前工作目录:
import os

current_dir = os.getcwd()
print(current_dir)
  1. 连接路径:
import os

path1 = '/path/to/dir'
path2 = 'file.txt'

full_path = os.path.join(path1, path2)
print(full_path)
  1. 检查路径是否存在:
import os

path = '/path/to/dir'

if os.path.exists(path):
    print("Path exists")
else:
    print("Path does not exist")
  1. 创建目录:
import os

new_dir = '/path/to/new/dir'

os.mkdir(new_dir)
  1. 列出目录下的文件和子目录:
import os

path = '/path/to/dir'

contents = os.listdir(path)
for item in contents:
    print(item)

这些是一些常见的路径操作方法,您可以根据您的需求进一步扩展和使用。

0