aschmid00
aschmid00

Reputation: 7158

python open() how to change set files name/title

If I open a file (image) in python with

f = open('/path/to/file.jpg', 'r+')

I have 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?

Upvotes: 2

Views: 5380

Answers (2)

JAB
JAB

Reputation: 21079

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

Upvotes: 2

Chris B.
Chris B.

Reputation: 90201

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'

Upvotes: 0

Related Questions