我們正在使用一個函式來匹配一個檔案模式,如果它匹配,我們正在運行一些作業,并最終從檔案夾中洗掉該檔案。但是,檔案模式匹配代碼出現了 "FileNotFoundError: [Errno 2] No such file or directory",當for回圈運行和一些檔案被洗掉時,這種情況發生的時間非常短,以至于我們無法在較低的環境中復制這個問題。有什么辦法能抓住這個錯誤或解決它。在這種情況下,'ABCD.XAF.XYJ250.A252.dat'檔案存在于檔案夾中,但作為其他作業的一部分被洗掉。
def poke(self, context)。
full_path = self.filepath
file_pattern = re.compile(self.filepattern)
os.chdir(full_path)
for files in sorted(os.listdir(full_path),key=os.path.getmtime) 。
if not re.match(file_pattern, files)。
self.log.info(files)
self.log.info(file_pattern)
else:
print("File Sensed"/span> files)
return True True
return False
錯誤:
檔案"File_Sensor_Operator.py",行25,in poke
for files in sorted(os.listdir(full_path),key=os.path.getmtime)。
檔案 "/usr/lib64/python3.6/genericpath.py", line 55, in getmtime
return os.stat(filename).st_mtime
FileNotFoundError: [Errno 2] No such file or directory: 'ABCD.XAF.XYJ250.A252.dat'
uj5u.com熱心網友回復:
IIUC,錯誤的發生是因為在for回圈開始后,你已經洗掉了一個檔案,這意味著它不再是由sorted(os.listdir(full_path),key=os.path.getmtime)回傳的可迭代檔案,然后拋出錯誤。
所以我認為,如果你把你的代碼的那一部分改成這樣,它就應該消失了:
all_files = sorted(os.listdir(full_path),key=os.path.getmtime)
for files in all_files:
if not re.match(file_pattern, files)。
這樣一來,迭代器就被分配給了一個變數,所以當你回圈瀏覽時,狀態就被保留了。
uj5u.com熱心網友回復:
你的問題是,你收集了所有的檔案,洗掉了一個,然后試圖通過每個檔案的屬性對它們進行排序(其中一個已經不存在了)
import os
with open("dat.dat", "w ") 。
pass: pass.
file_list = os.listdir(os.path.dirname(__file__) )
os.remove("dat.dat")
for file_name in sorted(file_list, key=os.path.getmtime)。
print(file_name)
你可以通過在排序前將檔案名和屬性分配給一個變數來解決這個問題。
import os
with open("dat.dat", "w ") 。
pass: pass.
file_list = {
filename:os.path.getmtime(filename)
for filename in os.listdir(os.path.dirname(__file__))
if os.path.exists(filename)
}
os.remove("dat.dat")
for file_name in sorted(file_list.keys(), key=file_list.get)。
print(file_name)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/318323.html
標籤:
上一篇:根據起始字母過濾出單詞
下一篇:將二分查找轉換為使用遞回
