我只想列出一个目录的文件,跳过子目录。
当前代码还列出了子目录中的文件,但这不是我想要的:
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)
目录中要处理的文件如下所示:
/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
期望输出:
['/headfolder/file.pdf','/headfolder/file2.pdf ']
files=[i for i in os.listdir() if os.path.isfile(i)]
编辑:
用于列出特定目录中的所有文件
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)