[英]Python: Importing multiple txt files and converting them into lists
我的 python 项目有多个 .txt 文件。 所有都是由行分隔的字符串列表。 以前,我已经导入了每个 txt 文件并使用
with open('general_responses.txt') as f:
general_responses = f.read().splitlines()
但是,我想使用 for 循环自动执行此操作以加快流程,以便我可以更轻松地将响应列表添加到我的项目中。 所以,这是我目前拥有的代码,而不是它的工作原理......
final_files = ['general_responses.txt', 'cat_responses.txt', 'dog_responses.txt']
for word in final_files:
with open(word) as f:
word = word[:-4]
word = f.read().splitlines()
所以当我跑
print (general_responses)
我的脚本应该从 txt 文件 general_responses.txt 打印出一个字符串列表
但是,这不起作用。 有什么建议?
编辑:
例如,general_responses.txt 将包含以下内容:
hi i'm fred
whats up
how are you doing today?
您想将每个文件的结果收集在一个单独的列表中(此处称为lines
):
final_files = ['general_responses.txt', 'cat_responses.txt', 'dog_responses.txt']
lines = []
for filename in final_files:
with open(filename) as f:
lines.extend(f.read().splitlines())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.