Python:从路径获取文件夹链

2024-05-12 13:14:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下路径作为输入:

path = "D:\dataset\raw\2018\fk180731\tuna_sand\20180805_215810_ts_un6k\image\i20180805_215810"

我想在脚本的目录中创建相同的文件夹链。我希望新文件夹链从“原始”文件夹开始。 例如:

D:\MY_SCRIPT_LOCATION\raw\2018\fk180731\tuna_sand\20180805_215810_ts_un6k\image\i20180805_215810

我试过了

head_tail = os.path.split(path)
print(head_tail[1])

但这只给出了最后一个文件夹的名称。你知道怎么做吗

谢谢

澄清一下:我希望脚本编辑输入路径并删除“raw”之前的所有内容。然后使用脚本的当前目录从“raw”开始创建文件夹链


Tags: pathimage路径脚本文件夹rawheaddataset
2条回答

您可以尝试以下方法:

import os
path='D:/dataset/raw/2018/fk180731/tuna_sand/20180805_215810_ts_un6k/image/i20180805_215810'
a=path.split('/')
a.pop(0)
a.pop(0)

new_path='D:/MY_SCRIPT_LOCATION/'+'/'.join(a)
os.makedirs(new_path)
print('success')

如果您只想打印路径,请使用print(path.replace('dataset','MY_SCRIPT_LOCATION'))

如果要将文件夹创建为新路径,请使用以下代码:

import os
path = 'D:\\dataset\\raw\\2018\\fk180731\\tuna_sand\\20180805_215810_ts_un6k\\image\\i20180805_215810'
path = path.replace('dataset','MY_SCRIPT_LOCATION')
print(path)
try:
    os.makedirs(path)
except:
    print('Cannot create a file when that file already exists')
print('Done')

相关问题 更多 >