Search code examples
pythonpython-os

how can i get the path plus the name of the first file in a folder and so on in python


I got this code and i need to take the first path of a file and the files name an have put it as a string

from pathlib import Path
from os import walk
import os
from posixpath import dirname
f = []
jhon = r'C:\Users\ioshu\Desktop\you'
for (dirpath, dirnames, filenames) in walk(jhon):
    f.extend(filenames)
    f.extend(dirnames)
    break
Ben1= filenames[:1]
Ben2= dirpath[:2]

dataFolder = Path(r'C:\Users\ioshu\Desktop\you')

print(Ben1 , dataFolder)
print(dataFolder)

The print (ben1, dataFolder) the output" of that file is C:\Users\ioshu\Desktop\you ['07a5iya4vfm91-DASH_720.mp4'] The problem is that i need the out put to be like this C:\Users\ioshu\Desktop\you\0q74nqluycm91-DASH_720


Solution

  • Using walk will walk the whole tree, which is overkill for your needs. You can simply

        first_file_name = os.listdir('/etc')[0]
    

    if you are sure there are only files, or:

    import os
    
    path = '/etc'  # any path you want
    first_file = None
    for i in os.listdir(path):
        file_path = os.path.join(path, i)
        if os.path.isfile(file_path):
            first_file = file_path
            break  # assuming you don't need to sort the names
    

    Always use os.path.join to join paths, works on Linux, Windows, MacOS and any other supported platform.

    PS: Ben1 = filenames[:1] returns a list with one element, not the element. If you need the element then: Ben1 = filenames[0].

    PS2: If you want to use pathlib then dataFolder / filenames[0] or something will help.