Python - 非递归地在给定目录中创建文件列表
Python - Creating a list of files in a given directory, non-recursively
我在处理本应如此简单的事情时遇到了困难 -
从给定目录路径中的文件创建列表。我怀疑这个问题与相对路径有关,但仍然无法使其正常工作。这是一个起点:
import sys, os.path
dir = os.path.abspath(sys.argv[1])
print(f'Given directory path: {dir}')
filelist = []
[filelist.append(os.path.abspath(item)) for item in os.listdir(dir)
if os.path.isfile(item) if not item.startswith('.')]
for file in filelist:
print(file)
- 仅限文件。没有子目录添加到列表中。
- 列表条目应包含文件的完整路径名。
- 非递归。仅指定文件夹中的文件。
- 跳过隐藏文件。
- 使用 os.walk(递归)并删除列表条目被认为是一种 hacky 解决方案。
更新
问题与 os.listdir 和相对路径有关,我笨拙的列表理解不必要地增加了组合的复杂性。按照评论中的建议修复列表理解使得将它们放在一起更加清晰和容易,并且它现在可以正常工作。工作代码如下:
filelist = [os.path.join(os.path.abspath(dir),file)
for file in os.listdir(dir)
if os.path.isfile(os.path.join(dir,file))
if not file.startswith('.')]
更新 2: 从我自己强加的列表理解监狱中解脱出来,我意识到也可以使用 next 和 os.walk:
filelist = [os.path.join(dir,file)
for file in next(os.walk(dir))[2]
if not file.startswith('.')]
我认为 glob 会排除隐藏文件。这应该会为您提供所提供路径中的文件列表。
from os.path import abspath, isfile, join
from glob import glob
files = [abspath(x) for x in glob(join(sys.argv[1], '*')) if isfile(x)]
问题是 os.path.abspath(item),其中 item 在目录中,必须假定该 item 在当前工作目录中,因为 os.listdir 只有 returns 对象相对于dir 参数。而是使用
os.path.abspath(os.path.join(dir,item)) 或者只是 os.path.join(dir,item)
我在处理本应如此简单的事情时遇到了困难 - 从给定目录路径中的文件创建列表。我怀疑这个问题与相对路径有关,但仍然无法使其正常工作。这是一个起点:
import sys, os.path
dir = os.path.abspath(sys.argv[1])
print(f'Given directory path: {dir}')
filelist = []
[filelist.append(os.path.abspath(item)) for item in os.listdir(dir)
if os.path.isfile(item) if not item.startswith('.')]
for file in filelist:
print(file)
- 仅限文件。没有子目录添加到列表中。
- 列表条目应包含文件的完整路径名。
- 非递归。仅指定文件夹中的文件。
- 跳过隐藏文件。
- 使用 os.walk(递归)并删除列表条目被认为是一种 hacky 解决方案。
更新
问题与 os.listdir 和相对路径有关,我笨拙的列表理解不必要地增加了组合的复杂性。按照评论中的建议修复列表理解使得将它们放在一起更加清晰和容易,并且它现在可以正常工作。工作代码如下:
filelist = [os.path.join(os.path.abspath(dir),file)
for file in os.listdir(dir)
if os.path.isfile(os.path.join(dir,file))
if not file.startswith('.')]
更新 2: 从我自己强加的列表理解监狱中解脱出来,我意识到也可以使用 next 和 os.walk:
filelist = [os.path.join(dir,file)
for file in next(os.walk(dir))[2]
if not file.startswith('.')]
我认为 glob 会排除隐藏文件。这应该会为您提供所提供路径中的文件列表。
from os.path import abspath, isfile, join
from glob import glob
files = [abspath(x) for x in glob(join(sys.argv[1], '*')) if isfile(x)]
问题是 os.path.abspath(item),其中 item 在目录中,必须假定该 item 在当前工作目录中,因为 os.listdir 只有 returns 对象相对于dir 参数。而是使用 os.path.abspath(os.path.join(dir,item)) 或者只是 os.path.join(dir,item)