给定文件的路径:
file = "/directory/date/2011/2009-01-11 This is a file's path/file.jpg"
如何快速将其替换为:
new_file = "/newdirectory/date/2011/2009-01-11 This is a file's path/file.MOV"
为“.MOV”更改“newdirectory”和“.jpg”的目录
答案 0 :(得分:3)
这可以用不同的方式完成,但这就是我要做的事情
首先更改扩展名。这可以通过像{/ 3>这样的os.path.splitext轻松完成
path = "/directory/date/2011/2009-01-11 This is a file's path/file.jpg"
new_file=os.path.splitext(path)[0]+".MOV"
这将路径设为
"/directory/date/2011/2009-01-11 This is a file's path/file.MOV"
现在要将目录更改为newdirectory,我们可以使用str.split, with maxsplit选项。
new_file=new_file.split('/',2)
最后使用join,用你喜欢的目录替换列表中的第二项,用'/'作为分隔符
new_file = '/'.join([new_file[0],"newdirectory",new_file[2]])
所以我们终于有了
"/newdirectory/date/2011/2009-01-11 This is a file's path/file.MOV"
总而言之,它归结为三行
new_file=os.path.splitext(path)[0]+".MOV"
new_file=new_file.split('/',2)
new_file = '/'.join([new_file[0],"newdirectory",new_file[2]])
答案 1 :(得分:0)
我会使用os.sep
import os
path = "/directory/date/2011/2009-01-11 This is a file's path/file.jpg"
path = os.path.splitext(path)[0] + '.mov'
path = path.split(os.sep, 2)
path[1] = 'newdirectory'
path = os.sep.join(path)
print path
<强>结果:强>
/newdirectory/date/2011/2009-01-11 This is a file's path/file.mov