如何在列表中获得文件路径?



我正在学习python。

我想在所有子目录中的所有文件的列表,然后选择一个随机文件并打开它(所有文件是不同的图像类型)。

现在,我得到:

Traceback (most recent call last):
File "c:UsersxxxOneDriveDesktoppythonProjecttest.py", line 20, in <module>
os.startfile(d)
FileNotFoundError: [WinError 2] Das System kann die angegebene Datei nicht finden: (file can not be found)

我想这是因为我只得到文件的名称,而不是路径?

我怎么能列出所有的文件路径,然后随机选择一个?

完整代码如下:

import random
import os
from os import walk
# folder path
dir_path = "M:/01_Bilder/01_Shootings"
# list to store files name
AllFiles = []
for (dir_path, dir_names, file_names) in walk(dir_path):
AllFiles.extend(file_names)
print(AllFiles)
d=random.choice(AllFiles)
print("file is " + d)
os.startfile(d)

我是python的新手,带着教程来到这里,但我还没有完全理解python是如何工作的。请耐心点。

os.walk的第三项只提供了文件的名称,而不是它们的整个路径。os.startfile然后在运行脚本的目录中搜索文件名。

你也必须结合包含文件夹的路径,os.walk给你的第一个项目,与文件名:

# NOTE: To avoid name conflicts, I'd recomment changing the name
# of this variable to not crash into your initial path.
# Therefore, dir_path -> current_dir_path
for (current_dir_path, dir_names, file_names) in walk(dir_path):
for file_name in file_names:
AllFiles.append(os.path.join(current_dir_path, file_name))

或者你可以使用一个工具为你做这件事,即pathlib,它给你Path对象,包括绝对路径。

import pathlib
...
AllFiles = [file for file in pathlib.Path(dir_path).rglob("*") if file.is_file()]

为了使您的代码工作,我改变了将文件添加到列表'ALLFiles'的方式:

import random
import os
from os import walk
# folder path
dir_path = "folder"
# list to store files name
AllFiles = []
for (dir_path, dir_names, file_names) in walk(dir_path):
for file in file_names:
AllFiles.append(dir_path + os.sep + file)
print(AllFiles)
d=random.choice(AllFiles)
print("file is " + d)
os.startfile(d)
我强烈推荐使用pathlib。它是一个更现代的处理文件的接口,可以更好地处理文件系统对象,包括路径、文件名、权限等。
>>> import random
>>> from pathlib import Path
>>> p = Path('/tmp/photos')
>>> files = [x for x in p.glob('**/*') if x.is_file()]
>>> random_file = random.choice(files)
>>> print(random_file)
/tmp/photos/photo_queue/KCCY2238.JPEG

它给了你简单的方法来处理你想对文件做的很多事情:

>>> file = files[0]
>>> file.name
'GYEP0506.JPG'
>>> file.stem
'GYEP0506'
>>> file.suffix
'.JPG'
>>> file.parent
PosixPath('/tmp/photos/photo_queue')
>>> file.parent.name
'photo_queue'
>>> file.parts
('/', 'tmp', 'photos', 'photo_queue', 'GYEP0506.JPG')
>>> file.exists()
True
>>> file.is_absolute()
True
>>> file.owner()
'daniel'
>>> file.with_stem('something_else')
PosixPath('/tmp/photos/photo_queue/something_else.JPG')

最新更新