仅列出目录的文件并忽略 python 的子目录
list only files of a directory and ignore the subdirectories with python
我想只列出目录的文件并跳过子目录。
当前代码还列出了子目录中的文件,但这不是我想要的:
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)
我想只列出目录的文件并跳过子目录。
当前代码还列出了子目录中的文件,但这不是我想要的:
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)