首页 > 解决方案 > 将目录中的文件列表转换为列表,以便可以迭代-python

问题描述

所以我想创建一个目录列表,以便我可以迭代它。目标是能够让函数查看列表并在每一行上运行该函数。这就是我所做的:

import re
import os
import json

#this is what should search a list all files in directory
def list_of_files():
    path = '/mnt/c/Users/deni/desktop/chatette/'
    files = os.listdir(path)
    for f in files:
        print(f)
        return(f)


#this is where the file is loaded
def load_file(filename):
    loadfile = open("filename, "r")
    replace_name = os.path.basename(loadfile.name)
    name_of_file = os.path.splitext(replace_name)[0]

    if loadfile.mode == 'r':
        contents = loadfile.read()
        remove_dashes = re.sub("-","", contents)
        remove_hashes =re.sub("##", "", remove_dashes)
        remove_intent =re.sub("intent", "", remove_hashes)
        remove_colan =re.sub(":", "", remove_intent)
        remove_generic =re.sub("Generic", "", remove_colan)
        remove_critical =re.sub("critical", "", remove_generic)
        remove_line_one=re.sub("<! Generated using Chatette v1.6.2 >", name_of_file, remove_critical)
        edited_contents = remove_line_one   
        #print(edited_contents)
        return(edited_contents)

#this is suppose to iterate the file and run the function for each file listed
listoffile = list_of_files()

for txt in listoffile:
    for i in list_of_files():
        if i.endswith(".xlsx"):
            load_file(txt)

这是我得到的回应

Traceback (most recent call last):
  File "generate.py", line 68, in <module>
    for txt in listoffile:
TypeError: 'NoneType' object is not iterable

你能帮我解决这个问题吗?

标签: pythonloopsiteration

解决方案


我能想到的有两种选择:

  • 返回文件列表
  • 使用生成器一次返回一个文件

我将从第一个开始,因为它更容易实现:

def list_of_files():
    path = '/mnt/c/Users/deni/desktop/chatette/'
    return os.listdir(path)

#...
listoffile = list_of_files()

for txt in listoffile:
    if i.endswith(".xlsx"):
        load_file(txt)

第二个在内存使用方面更为优化,因为它不会在返回之前预先分配文件列表:

def list_of_files():
    path = '/mnt/c/Users/deni/desktop/chatette/'
    files = os.listdir(path)
    for f in files:
        print(f)
        yield f
#...
listoffile = list_of_files()

for txt in listoffile:
    if i.endswith(".xlsx"):
        load_file(txt)

推荐阅读