我正在努力學習python。
我想列出所有子目錄中的所有檔案,然后選擇一個隨機檔案并打開它(所有檔案都是不同的影像型別)。
目前,我得到:
Traceback (most recent call last):
File "c:\Users\xxx\OneDrive\Desktop\pythonProject\test.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 是如何作業的。請耐心等待。
uj5u.com熱心網友回復:
第三項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提供包含絕對路徑的 -objects。
import pathlib
...
AllFiles = [file for file in pathlib.Path(dir_path).rglob("*") if file.is_file()]
uj5u.com熱心網友回復:
為了使您的代碼正常作業,我更改了將檔案添加到串列“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)
uj5u.com熱心網友回復:
我強烈建議使用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')
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/493601.html
下一篇:如何忽略已經存在的檔案?
