代码之家  ›  专栏  ›  技术社区  ›  Simon Lindgren

加快文件读写速度

  •  0
  • Simon Lindgren  · 技术社区  · 4 年前

    我想做到这一点,如果可能的话,我想做得更快:

    1. 浏览以下列表 users .
    2. 读取目录中的所有文件,其名称包括用户名。
    3. 抓取每个这样的文件的内容,并将其连接到每个用户的一个文件中。

    我有这段代码,但它非常慢:

    for u in users:
        content = ""
        contentfiles = glob.glob("raw_data/" + "*_" + str(u) + ".txt")
        for c in contentfiles:
            txt = open(c, "r").read()
            content += txt
        with open("docs/" + str(u) + ".txt", "w") as outfile:
            outfile.write(content)
    

    是否有更快的方法来实现这一点?我有40万用户,这大约每秒运行一个文件=18小时。

    编辑:将glob移出循环将产生更快的结果

    datafiles = glob.glob("raw_data/*.txt")   
    
    for u in users:
            content = ""
            filestring = "_" + str(u) + ".txt"
            contentfiles = [i for i in datafiles if filestring in i]
            for c in contentfiles:
                txt = open(c, "r").read()
                content += txt
    
    0 回复  |  直到 4 年前
        1
  •  0
  •   Keldorn    4 年前

    基于以下假设 glob 是瓶颈,那么在编辑列表过滤是新的瓶颈,这里有一个命题:

    • 移动 glob 跳出循环,只做一次
    • 如果有的话,只进行一次列表筛选
    • 不要将内容存储在临时变量中
    datafiles = glob.glob("raw_data/*.txt")   
    userfiles = {} # Dictionary of "user: [file list]"
    
    # Prepare the file list
    for file in datafiles:
        user = file.split('.')[-2].split('_')[-1]
        ufiles = userfiles.get(user, default=[])
        ufiles.append(file)
        userfiles[user] = ufiles
    
    # Loop over the list
    for user, ufiles in userfiles.items():
        with open("docs/{}.txt".format(user), "w") as outfile:
            for infile in ufiles:
                outfile.write(infile.read())
    

    你甚至可以根本不过滤每个用户的文件,只在任意顺序的文件上循环 datafiles 这意味着要打开 outfile 处于追加模式( a ),这样原始内容就不会被用户的每个新文件覆盖。