Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select the first file in a directory?

Tags:

python

file

I'm trying to process some files in a directory without knowing their name, and one by one. So I've used os.listdir(path) to list files.

So I have to list files at each call of my function. The problem is when there is a lot of files (like 2000), it takes a loooooong time to list each file and I just want the first one.

Is there any solution to get the first name without listing each files ?

like image 298
Lerenn Avatar asked Jul 24 '15 14:07

Lerenn


People also ask

Which is the start first directory?

File System Organization The first directory in the file system is called the root directory. The root directory contains files and subdirectories, which contain more files and subdirectories and so on and so on.

How do I jump to a directory?

To navigate to your home directory, use "cd" or "cd ~" To navigate up one directory level, use "cd .." To navigate to the previous directory (or back), use "cd -"


4 Answers

os.listdir(path)[0]

It would be faster than 'listing' (printing?) each filename, but it still has to load all of the filenames into memory. Also, which file is the first file, do you only want whichever one comes first or is there a specific one you want, because that is different.

like image 144
Michael Neylon Avatar answered Oct 02 '22 19:10

Michael Neylon


If your goal is to process each file name, use os.walk() generator:

Help on function walk in module os:

walk(top, topdown=True, onerror=None, followlinks=False)
    Directory tree generator.
like image 44
helloV Avatar answered Oct 03 '22 19:10

helloV


It seems like you're trying to process the files en masse, and you'll be iterating through all the files at some point. Instead of having calling the method every time that you enter your function, why not have a global parameter so that you only load the list once? So, for example, instead of:

import os
def foo(path):
    os.listdir(path)[0]

you have:

import os
fnames = os.listdir(path)
def foo(path):
    fnames[0]
like image 20
Nikhil Shinday Avatar answered Oct 02 '22 19:10

Nikhil Shinday


To get the first filename without having to scan the whole directory, you have to use the walk function to get the generator and then you can use next() to get the first value of the generator.

folder_walk = os.walk(path)
first_file_in_folder = next(folder_walk)[2][0]

print(first_file_in_folder)
# "firstFile.jpg"
like image 24
pubkey Avatar answered Oct 02 '22 19:10

pubkey