python open() 如何更改文件名/标题
如果我在Python中打开一个文件(比如图片),用的是
f = open('/path/to/file.jpg', 'r+')
我有一个函数 f.title()
,它会返回这个文件的完整路径。那我该怎么把打开的文件的名字或者显示的标题改成别的呢?
2 个回答
0
对我来说这个方法不管用(我用的是Python 2.6,操作系统是Windows);我必须使用“name”这个属性:
>>> f = open(r'C:\test.txt', 'r+')
>>> f.title()
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'file' object has no attribute 'title'
>>> f.name
'C:\\test.txt'
根据文档, “name”是只读的。很遗憾,你不能随便给文件对象设置其他属性:
>>> f.title = f.name
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'file' object has no attribute 'title'
2
你肯定不能用 open
来改变文件名。你应该使用 os.rename
。
不过,如果你只是想在程序里改变文件的名字,但不想改变实际的文件名,那你为什么要这么做呢?这样做有什么意义呢?我想如果你在用 Python 3,可以把文件对象的缓冲区分离出来,然后给它一个你想要的名字,当然在 Python 2.6 也可以这么做,但我在 Python 2.6 的 file
对象或 io
模块的文档里没看到 detach
方法的说明。总的来说,我不太明白这样做的意义……
等等,如果你只是想要文件名用在别的地方,而不一定要改变名字本身:
import os.path
f = open('/path/to/file.jpg', 'r+')
print(os.path.basename(f.name)) #don't include the parentheses if you're working in Python 2.6 and not using the right __future__ imports or working in something prior to 2.6
这段代码会输出 'file.jpg'。不过如果 blob.filename
是自动赋值的,我不确定这对你有没有帮助,除非你愿意去继承 blob
是什么类……