python多线程读取文件夹下的文件_是否可以使用python多线程从文件夹数读取文件数,并处理这些文件以获得组合结果?...
我認(rèn)為學(xué)習(xí)使用線程的最簡(jiǎn)單方法是在concurrent.futures模塊中使用ThreadPoolExecutor類,因?yàn)樗韧ǔ5耐絝or循環(huán)多了幾行。尤其是在Python3中,但這可以適用于Python2.7。在
基本上你有一個(gè)線程池(一堆)等待工作。Work通常只是一個(gè)方法/函數(shù),它與參數(shù)一起發(fā)送到池,ThreadPool處理其他所有事情(將任務(wù)分配給可用的資源并進(jìn)行調(diào)度)。在
假設(shè)我的日志目錄結(jié)構(gòu)如下:~ ? tree log
log
├── 1.log
├── 2.log
├── 3.log
└── schedules
├── 1.log
├── 2.log
└── 3.log
1 directory, 6 files
因此,首先得到文件列表(Python3)。在
^{pr2}$
每個(gè)文件(現(xiàn)在只是一個(gè)字符串變量)就是你希望線程處理的。因此,您有一個(gè)通用方法,接受一個(gè)file參數(shù),在每個(gè)文件中找到感興趣的字符串?;旧鲜且粯拥?#xff0c;如果你做了一個(gè)普通的Python程序,比如:def find_string(file):
# insert your specific code to find your string
# including opening the file and such
# returning values also possible see further down
print(file)
現(xiàn)在您只需將這些工作發(fā)送到ThreadPool。在from concurrent.futures import ThreadPoolExecutor
# We can use a with statement to ensure threads are cleaned up promptly
with ThreadPoolExecutor() as executor:
# Basically the same as if you did the normal for-loop
for file in list_of_files:
# But you submit your method to the Pool instead.
future = executor.submit(find_string, file) # see future.result() too
print("All tasks complete")
這里有一個(gè)很好的完整示例here,搜索ThreadPoolExecutor Example,它確實(shí)會(huì)打開(kāi)一個(gè)網(wǎng)站列表并以字節(jié)為單位打印大小。你可以修改成文件搜索。在
這里的瓶頸可能是大量的文件,這將是磁盤讀取速度。如果您有多個(gè)磁盤上的日志文件,那將是一個(gè)解決方案。在
另一個(gè)建議是多線程通常用于網(wǎng)絡(luò)操作或I/O,因此讀取文件是一個(gè)很好的用途。不過(guò),你也在做一些處理。根據(jù)CPU的密集程度,您可能需要查看ProcessPoolExecutor中使用multiprocessing模塊的對(duì)象。它與ThreadPoolExecutor共享相同的接口。在
希望這是有道理的。在
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的python多线程读取文件夹下的文件_是否可以使用python多线程从文件夹数读取文件数,并处理这些文件以获得组合结果?...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: mysql主从配置笔记_MySQL主从配
- 下一篇: python tcl 控件_在Tkint