我有一個檔案串列,我想檢測它們是否存在于子目錄中,我已經很接近了,但我被困在最后一步(第 5 步)。
采取的步驟
- 從提供的文本檔案中獲取檔案名
- 將檔案名保存為串列
- 回圈遍歷之前保存的檔案名串列
- 回圈遍歷目錄和子目錄以識別檔案是否存在
- 將檔案名保存在找到的第二個串列中
提供的文本檔案有一個串列,例如:
- 測驗檔案1.txt
- 測驗檔案2.txt
- 測驗檔案3.txt
- 測驗檔案4.txt
- 測驗檔案5.txt
其中只有 testfile1-4 實際上存在于(子)目錄中。
預期的輸出是一個串列,例如 ['testfile1.txt', 'testfile2.txt', 'testfile3.txt', 'testfile4.txt']。
代碼
import os.path
from os import path
import sys
file = sys.argv[1]
#top_dir = sys.argv[2]
cwd = os.getcwd()
with open(file, "r") as f: #Step 1
file_list = []
for line in f:
file_name = line.strip()
file_list.append(file_name) #Step 2
print(file_list)
for file in file_list: #Step 3
detected_files = []
for dir, sub_dirs, files in os.walk(cwd): #Step 4
if file in files:
print(file)
print("Files Found")
detected_files.append(file) #Step 5
print(detected_files)
它列印出來的內容:
Files Found
testfile1.txt
['testfile1.txt']
Files Found
testfile2.txt
['testfile2.txt']
Files Found
testfile3.txt
['testfile3.txt']
Files Found
testfile4.txt
['testfile4.txt']
uj5u.com熱心網友回復:
您當前的流程如下所示
with open(file, "r") as f: #Step 1
...
for file in file_list: #Step 3
detected_files = []
...
for dir, sub_dirs, files in os.walk(cwd): #Step 4
...
您可以看到,在每次迭代中,for file in file_list:您都會創建一個新的空detected_files串列 - 丟失之前保存的所有資訊。
detected_files應該做一次
detected_files = []
with open(file, "r") as f: #Step 1
...
for file in file_list: #Step 3
...
for dir, sub_dirs, files in os.walk(cwd): #Step 4
...
我會使用一個集合進行成員資格測驗,并將所有找到的檔案名保存在一個集合中(以避免重復)。
detected_files = set()
with open(file, "r") as f: #Step 1
file_list = set(line.strip() for line in f)
for dir, sub_dirs, files in os.walk(cwd): #Step 4
found = file_list.intersection(files)
detected_files.update(found)
如果您愿意,如果找到所有檔案,您可以縮短該程序。
for dir, sub_dirs, files in os.walk(cwd): #Step 4
found = file_list.intersection(files)
detected_files.update(found)
if detected_files == file_list: break
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/462008.html
下一篇:如何按條件將代碼應用于資料幀?
