tags:

views:

49

answers:

2

if i open a file (image) in python with f = open('/path/to/file.jpg', 'r+') i have the a function f.title() and i get the full path of the file back. how can i change the opened files name/repr/title to something else?

+2  A: 

You don't change filenames using open, that's for sure. You'll want to use os.rename.

But if you're trying to change the name the file has within your program but NOT the actual filename, why are you trying to do that/what would be the point in that? I guess you could detach the buffer from the file object and assign it to a new object with the title you want, if you're working with Python 3 (thought you could do it in Python 2(.6) as well, but don't see any mention of the detach method in the documentation of the Python 2.6 file object or its io module), but really, I don't quite see the point...

Oh wait, if you just want the filename for use elsewhere and don't necessarily need to change the name itself:

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

This will output 'file.jpg'. Not sure if it helps you if blob.filename is an automatic assignment, though, unless you're willing to subclass whatever class blob is...

JAB
i open the file and i push it up to my appengine. i want to change the files name to have only the filename stored as the blob.filename instead of the full path i uploaded it from.
aschmid00
@aschmid00: Yeah, I realized that that was probably what you wanted. See my updated answer.
JAB
ok but how do i set this name to the opened files metadata before i multipart_encode the file to send it up to the site?
aschmid00
@aschmid00: You probably should edit the original question, or ask another question, rather than look for solutions in the comments.
Chris B.
A: 

It doesn't work for me (Python 2.6, on Windows); I have to use the "name" attribute:

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

According to the documentation, "name" is read-only. And unfortunately, you can't set arbitrary attributes on file objects:

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