如何根據我應該擁有的檔案的 txt 檢查目錄中缺少哪些檔案?
EG 這是我應該擁有的檔案串列
A
B
C
D
E
F
G
H
I
但在我的目錄中,我只有
A.npy
B.npy
C.npy
D.npy
所以我想做一個可以產生這樣的result.txt的腳本:
A [存在]
B [存在]
C [存在]
D [存在]
E [不存在]
F [不存在]
G [不存在]
H [不存在]
I [不存在]
這是我目前擁有的腳本,但它似乎不起作用,因為它將所有檔案注冊為“不存在”:(
import os
import copy
import pandas as pd
import shutil
from pathlib import Path
# read training files.txt
path_to_file = 'xxxxxxxxxxxxxxxxxx/train_files_CS/all_training_CSmaster.txt'
path = 'xxxxxxxxxxx/train_files_CS'
# list of training npy files in directory
lof = []
for (dirpath, dirnames, filenames) in os.walk(path):
lof.append(filenames)
lof = [x[:len(x) - 4] for x in lof[0] if x[0] == 'P']
#print(lof)
# new file to be written into
f = open('check_training.txt', 'w')
existing_files = 0
missing_files = 0
trfiles = []
with open(path_to_file) as file:
for line in file:
#print(line.rstrip())
trfiles.append(line)
for x in trfiles:
if x in lof:
existing_files =1
f.write(x)
f.write("...[exists] \n")
else:
missing_files =1
f.write(x)
f.write(" ...[doesn't exist] \n")
f.close()
print("\nthe missing files are:", missing_files,"\n")
print("the existing files are:",existing_files,"\n")
任何幫助表示贊賞,謝謝!:)
uj5u.com熱心網友回復:
在解決以下兩個問題后,您的程式對我有用:
第一期
lof = [x[:len(x) - 4] for x in lof[0] if x[0] == 'P']
我不認為您只想列出以字母“P”開頭的檔案。也許您在進行了一些除錯或其他操作后錯誤地將其留在了其中。要獲取所有檔案名,請洗掉該if x[0] == 'P'部分:
lof = [x[:len(x) - 4] for x in lof[0]]
第 2 期
with open(path_to_file) as file:
for line in file:
#print(line.rstrip())
trfiles.append(line)
這不會洗掉換行符,因此您最終會得到['a\n', b\n' 等]`,其元素在下一步的比較中不匹配。用這個:
with open(path_to_file) as file:
trfiles = file.read().splitlines()
通過這兩個更改,您應該會發現您獲得了預期的輸出。
其他提示
有很多地方可以通過使用串列推導而不是 for 回圈來使代碼更簡潔和可讀。例如
lof = []
for (dirpath, dirnames, filenames) in os.walk(path):
lof.append(filenames)
可:
lof = [filenames for (dirpath, dirnames, filenames) in os.walk(path)]
此外,x[:len(x) - 4]對于從檔案名中洗掉擴展名也不是很健壯(因為您可以擁有具有 4 個字母的檔案,例如 .html、.docx 等)。使用os庫函式拆分擴展:
lof = [os.path.splitext(x)[0] for x in lof[0]]
uj5u.com熱心網友回復:
您可以使用 Python 的內置os.path.isfile函式:
import os
os.path.isfile(path_to_file)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/526107.html
標籤:Python文件io
上一篇:FileSystemRights中的“269681087”代表什么?
下一篇:如何打開txt檔案的超鏈接
