如何解决将目录中的文件列表转换为列表,以便可以被执行-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)
,
在“ list_of_files”函数的for循环中,您仅通过1条路径进行迭代即可返回。然后打印并返回该路径。
在循环结束后,您需要返回“文件”而不是“ f”。
def list_of_files():
path = '/mnt/c/Users/deni/desktop/chatette/'
files = os.listdir(path)
for f in files:
print(f)
return(f)
所以它必须是
def list_of_files():
path = '/mnt/c/Users/deni/desktop/chatette/'
files = os.listdir(path)
for f in files:
print(f)
return(files)
,
查看堆栈跟踪:
Puppeteer script is working (headless:false) ....
Captcha appears on my chromium screen
I solve it manually and the next screen appears (Which would happen if there were no captcha)
Help=> Puppeteer picks up the "current" (post-captcha) page and continues execution....
我们看到问题是Traceback (most recent call last):
File "generate.py",line 68,in <module>
for txt in listoffile:
TypeError: 'NoneType' object is not iterable
,也就是说for txt in listoffile:
是listoffile
这意味着None
返回None。我最好的猜测是您发布的目录中没有文件:list_of_files()
您可能还希望'/mnt/c/Users/deni/desktop/chatette/'
到list_of_files()
,而不是循环内的单个文件。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。