python - 将目录中的文件列表转换为列表,以便可以迭代-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
你能帮我解决这个问题吗?
解决方案
我能想到的有两种选择:
- 返回文件列表
- 使用生成器一次返回一个文件
我将从第一个开始,因为它更容易实现:
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)
推荐阅读
- azure-devops - 不知道如何在 Azure DevOps Server 中设置布尔工作项字段以显示 Yes/No 而不是 True/False
- java - 如何使用 websocket 客户端侦听 rest api
- bash - 除非我不调用脚本 X,否则 bash 如何不完成此循环并且只处理 1 个项目?
- php - 如何创建数组的交集类型
- javascript - 使用动态递增值创建加载条
- ruby - 如何在变量和类之间传递块
- javascript - 如何从 JS 中的外部 url 解码多维 JSON?
- java - Spring 配置文件未从 application.properties 读取值
- python - 将文本中的字母添加到字典中而无需标点符号的功能
- mysql - 错误 1005 (HY000) mySql,在小型数据库上