我有一个csv文件文件夹。我想获得一个列表,其中每个元素都是文件所有行的列表(因此,为列表列表)。
我尝试了以下方法:
from os import listdir
folder = listdir("folder")
for files in folder:
individualFiles = open(f"folder/{files}", "r")
alist = individualFiles.readlines()
但这只会返回包含所有数据的巨大列表,而不是列表列表。
我能做什么?
我是一个初学者,我正在尝试学习编程的逻辑,因此,如果解决方案不需要花哨的功能但需要逻辑,我将不胜感激。
您代码中的问题只是您分配给alist
:
alist = individualFiles.readlines()
而不是附加到它:
alist.append(individualFiles.readlines())
并且您将必须在循环之前创建一个列表: alist = list()
您的代码对此做了一些修改,以解释其逻辑:
from os import listdir
# Name of the folder containing the files
folder_path = "textfiles"
# Get a list of filenames
filenames = listdir(folder_path)
# List to store the content of the files
files_content = list()
# For each file
for filename in filenames:
# Create the filepath
file_path = f"{folder_path}/{filename}"
# Open the file (using "with" for file opening will autoclose the file at the end. It's a good practice)
with open(file_path, "r") as f:
# Get the file content
file_content = f.readlines()
# Append the conten to the list
files_content.append(file_content)
print(files_content)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句