Python os.path.split,在不影响路径的情况下更改文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18950668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:23:10  来源:igfitidea点击:

os.path.split, changing file name with out compromising the Path

pythondjango

提问by ashir nasir

i have followed Python get file name and change & save it in variable. which work fine and change the file name as required.

我已经按照Python 获取文件名并更改并将其保存在变量中。工作正常并根据需要更改文件名。

but now i am facing problem with path where the file is getting saved. as the file is getting saved in "media/ok_abc.txt" whereas it should be media/documents/ok_abc.txt

但现在我面临文件保存路径的问题。因为文件被保存在“ media/ok_abc.txt”中,而它应该是media/documents/ok_abc.txt

e.g.

例如

docfile = /media/documents/abc.csv after applaying below instruction

docfile = /media/documents/abc.csv 应用以下指令后

filename = os.path.splitext(docfile.name)[0]
newfilename = 'ok_%s.txt' % filename

am able to change the file name but the path is getting reduced as /media/ok_abc.txt, it should be /media/documents/abc.txt

我能够更改文件名,但路径越来越少,为/media/ok_abc.txt,它应该是/media/documents/abc.txt

how i can change the file name with out compromising on the Path

如何在不影响路径的情况下更改文件名

回答by ledzep2

Extract the directory from the full file path, and later add it back.

从完整文件路径中提取目录,然后将其添加回来。

path, filename = os.path.split(docfile)
filename = os.path.splitext(filename)[0]
newfilename = 'ok_%s.txt' % filename
newpath = os.path.join(path, newfilename)