2010-07-01 27 views

回答

2

您不會使用open更改文件名,這是肯定的。你會想要使用os.rename

但是,如果你想改變你的程序中的文件名,但不是實際的文件名,你爲什麼要這麼做/這將是什麼?我想你可以從文件對象中分離出緩衝區,並將它分配給一個帶有你想要的標題的新對象,如果你正在使用Python 3的話(也可以用Python 2(.6)來做,但是不要「看不到的detach方法的任何提及的Python 2.6 file對象或其io模塊)的文件中,但說真的,我不太明白這一點......

哦,等等,如果你只是想在文件名在其他地方使用,不一定需要更改名稱本身:

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 ...

+0

我打開文件,並將其推到我的appengine。我想將文件名更改爲只有文件名存儲爲blob.filename而不是我上傳的完整路徑。 – aschmid00 2010-07-01 16:32:36

+0

@ aschmid00:是的,我意識到這可能是你想要的。看到我更新的答案。 – JAB 2010-07-01 16:34:52

+0

好的,但我怎麼設置這個名稱到打開的文件元數據之前我multipart_encode文件發送到網站? – aschmid00 2010-07-01 16:42:05

0

它不適用於我(Python 2.6,在Windows上);我必須使用「名稱」屬性:

>>> 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' 

根據the documentation,「name」是隻讀的。不幸的是,你不能在文件對象上設置任意屬性:

>>> f.title = f.name 
Traceback (most recent call last): 
    File "<console>", line 1, in <module> 
AttributeError: 'file' object has no attribute 'title'