替换文件路径和扩展名元素的最快方法?

2024-04-19 23:47:39 发布

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

给定文件路径:

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"

同时更改“newdirectory”的目录和“.jpg”的“.MOV”


Tags: 文件path路径目录newdateisthis
2条回答

好吧,这可以用不同的方法来做,但我会这样做

先换分机。这可以很容易地通过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]])

我会利用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

相关问题 更多 >