os.path.split,改变文件名与妥协的Path [英] os.path.split, changing file name with out compromising the Path

查看:439
本文介绍了os.path.split,改变文件名与妥协的Path的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经遵循 Python获取文件名并更改&保存在变量中。哪些工作正常,并根据需要更改文件名。



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


$ b $例如



docfile = /media/documents/abc.csv
在应用下面说明

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

可以更改文件名,但路径随着 /media/ok_abc.txt 而减少,应该是 / media/documents/abc.txt



我可以如何在路径上修改文件名来妥协。

解决方案

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

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


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

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

e.g.

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

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

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

解决方案

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)

这篇关于os.path.split,改变文件名与妥协的Path的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆