可以使用os
模块中的walk
函数来遍历指定目录及其子目录下的所有文件和文件夹。然后,可以使用os.path
模块中的relpath
函数来将路径转换为相对路径。
以下是一个示例代码:
import os
# 遍历指定目录及其子目录下的所有文件和文件夹
def change_paths_to_relative(directory):
for root, dirs, files in os.walk(directory):
# 遍历文件
for file in files:
# 获取文件的绝对路径
abs_path = os.path.join(root, file)
# 将绝对路径转换为相对路径
rel_path = os.path.relpath(abs_path, directory)
# 打印相对路径
print(rel_path)
# 遍历文件夹
for dir in dirs:
# 获取文件夹的绝对路径
abs_path = os.path.join(root, dir)
# 将绝对路径转换为相对路径
rel_path = os.path.relpath(abs_path, directory)
# 打印相对路径
print(rel_path)
# 调用函数,传入指定目录的路径
change_paths_to_relative('your_directory_path')
在上面的示例中,change_paths_to_relative
函数接受一个目录的路径作为参数,然后使用os.walk
函数遍历该目录及其子目录下的所有文件和文件夹。对于每个文件和文件夹,使用os.path.relpath
函数将其绝对路径转换为相对路径,并打印出来。
你可以根据自己的需求进一步修改代码,例如将相对路径存储到一个列表中,或者将相对路径写入文件等。