简体   繁体   中英

list only files of a directory and ignore the subdirectories with python

I would like to list only the files of a directory and skip the subdirectories.

The current code lists also the files in the subdirectories but that's not what I want:


import os 

list_files = []    
for root, dirs, files in os.walk(input_folder):
        for filename in files:
            joined = os.path.join(input_folder, filename)
            list_files.append(joined)

The files in the directory to process look like this:

/headfolder/subfolder/subfile.pdf     #ignore this directory
/headfolder/subfolder2/subfile.pdf    #ignore this directory
/headfolder/file.pdf                  #get this path 
/headfolder/file2.pdf                 #get this path  

desired output:

['/headfolder/file.pdf','/headfolder/file2.pdf ']
files=[i for i in os.listdir() if os.path.isfile(i)]

Edit:

for list all files in specific direcotry

import os
from os import listdir
from os.path import isfile, join

input_folder = 'headfolder/'
list_files = []

files = [f for f in listdir(input_folder) if isfile(join(input_folder, f))]
for filename in files:
    joined = os.path.join(input_folder, filename)
    list_files.append(joined)

print(list_files)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM