BoJack Horseman
BoJack Horseman

Reputation: 4450

Getting a filename and save it in a variable in Python

I want to get the name of a file that gets created by some other process inside a folder. It's in a path where only this file exists. It's in this path:

/directory/which/only/contains/this/one/file/

The file's full filename could then be for example:

/directory/which/only/contains/this/one/file/xZqsdtae123456.txt

How can I get the name of this file (from the example above: xZqsdtae123456.txt) and then save it in a variable ?

Upvotes: 0

Views: 4454

Answers (1)

sebastian_oe
sebastian_oe

Reputation: 7340

Assuming the generated file is the only one (as stated):

import os
yourfile = os.listdir("/home/user/Desktop/directory_which_only_contains_this_one_file")[0]

Upvotes: 3

Related Questions