Richard
Richard

Reputation: 63

Get name of created file

I'm creating files in python and I want to print the full path of the already file created. Example:

dt = datetime.datetime.now()
datetime = dt.strftime("%d-%m")
output = open("c:\path\to\file_"+datetime+".txt","w")

How can I print the final name of the created file?

I tried:

print (output)

but it gives me a rare string.

Upvotes: 0

Views: 90

Answers (2)

KLAS R
KLAS R

Reputation: 62

open() method doesn't return anything relevant. You can try on below methods...

1.print(output.__file__)


2. Import os
     os.path.abspath("filename.ext"). # it will add the cwd to file name or if iterating the real path
    os.path.dirname("filename.ext")
    os.path.dirname("filename.ext") 

3. Files= os.listdir(os.getcwd()) # it will list the files in cwd(you can give any path)
    for i in files:
        print(os.path.abspath(i))

Upvotes: 0

AKX
AKX

Reputation: 168957

For real file objects such as that,

print(output.name)

Upvotes: 1

Related Questions