簡體   English   中英

Python循環處理文本文件

[英]Python process text files in a loop

我在同一文件夾中有10個文本文件。 我想在for循環中分別處理每個文本文件。

def qwerty():
    with open('file.txt') as f:
       dicts = {}
       for words in f:
          split_words = reg.finditer(words)
          for line in split_words:
             group1 = line.group(1)
             if group1 not in dicts:
                dicts[group1] = 1
             else:
                dicts[group1] += 1 
     return dicts

這是我處理單個文本文件的代碼。 如何運行一個循環,一個接一個地處理我擁有的所有文本文件? 因此,文本文件的數量與for循環中的迭代次數相對應。

您可以使用os模塊遍歷當前目錄中的所有文件,並僅將txt文件過濾為:

import os

for file_name in os.listdir("./"):
    if file_name.endswith(".txt"): # Add some other pattern if possible
        # Call your method here

您的當前目錄還將包含其他文件,這些文件可能不會被過濾。因此,將txt文件移動到單獨的位置是一個更好的主意。

您可以枚舉文件夾中的文件,並在for循環中使用它

import os
from glob import glob

def qwerty(folder_path="."):
    for filename in glob(os.path.join(folder_path, "*.txt")):
        ... do your processing

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM