我正在執行下面的python代碼。python的Windows磁盤使用問題
我在一個文件夾(「文章」)上運行它有幾百個子文件夾和240,226個文件。
我正在計時執行。起初時間非常穩定,但在100,000個文件後變爲非線性。現在時間(我以10,000個文件間隔計時)可以在30,000左右(或不是)之後變爲非線性。
我有任務管理器打開,並通過python.exe關聯減速到99%的磁盤使用情況。我完成了gc-collect()。 dels等,關閉Windows索引。我已重新啓動Windows,清空垃圾(我有幾百GB免費)。沒有什麼幫助,如果有的話,磁盤使用似乎越來越不穩定。
很抱歉的長期職位 - 感謝您的幫助
def get_filenames():
for (dirpath, dirnames, filenames) in os.walk("articles/"):
dirs.extend(dirnames)
for dir in dirs:
path = "articles" + "\\" + dir
nxml_files.extend(glob.glob(path + "/*.nxml"))
return nxml_files
def extract_text_from_files(nxml_files):
for nxml_file in nxml_files:
fast_parse(nxml_file)
def fast_parse(infile):
file = open(infile,"r")
filetext = file.read()
tag_breaks = filetext.split('><')
paragraphs = [tag_break.strip('p>').strip('</') for tag_break in tag_breaks if tag_break.startswith('p>')]
def run_files():
nxml_files = get_filenames()
extract_text_from_files(nxml_files)
if __name__ == "__main__":
run_files()
如果可以,請升級到Python 3.5;你的代碼似乎沒有使用特定的版本特性,並且使用新的['os.scandir']重新實現了'os.walk'(https://docs.python.org/3/library/os.html#os .scandir)功能。雖然'os.walk'不通過它的接口向你提供免費的'stat'信息,它執行的磁盤I/O要少得多;在Python <= 3.4時,它必須讀取文件的完整列表(少量I/O操作,搜索次數有限),然後將所有文件和目錄統統分開(在你的情況下,大約100,000次隨機讀取) 。使用'os.scandir'消除〜100,000'stats'。 – ShadowRanger
根據[Python 3.5發行說明](https://docs.python.org/3/whatsnew/3.5.html#whatsnew-pep-471),'os.scandir'在'os.walk'中使用無縫地將Windows系統中「os.walk」的速度提高了7-20倍。這是巨大的,如果你掃描了超過十萬個文件,你幾乎肯定會從加速中受益。 – ShadowRanger