【问题标题】:How can I get a list of lists out a folder of files in python?如何从python中的文件文件夹中获取列表列表?
【发布时间】:2020-11-12 19:12:29
【问题描述】:

我有一个 csv 文件的文件夹。我想得到一个列表,其中每个元素都是文件所有行的列表(因此,列表列表)。

我尝试了以下方法:

from os import listdir
folder = listdir("folder") 
for files in folder:
    individualFiles = open(f"folder/{files}", "r")
    alist = individualFiles.readlines() 

但这只会返回一个包含所有数据的巨大列表,而不是列表。

我能做什么?

我是一个初学者,我正在尝试学习编程的逻辑,所以如果解决方案不需要花哨的功能而是逻辑,我将不胜感激。

【问题讨论】:

  • 除其他外......列表必须附加。将列表初始化为mylist = [],然后在每次迭代中使用mylist.append([file_content])。这会将每个文件的内容放入父列表的列表元素中。
  • 但是我怎样才能独立读取每个文件的内容呢?使用“.readlines()”我只得到一个包含每个文件数据的列表。

标签: python list csv


【解决方案1】:

您的代码中的问题只是您分配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)

【讨论】:

  • 功能性答案,但对于手头的任务来说太过分了。另外,文件流对象现在返回一个可迭代对象,因此在技术上不再需要 readlines()
【解决方案2】:

一个非常简单的方法如下例所示。

步骤/逻辑:

  • 收集文件。我使用glob 库来执行此操作,因为glob 返回完整文件路径,因此无需自己构建。
  • 遍历列表中的每个文件。
  • 使用with 语句读取文件。这对于确保自动关闭文件句柄很重要
  • 将文件内容列表附加到container 列表中。

示例代码:

import os
from glob import glob

files = glob('/home/user/Desktop/list_of_files/*.csv')
container = []

for file in files:
    with open(file, 'r') as f:
        container.append(list(f))

文件:

['/home/user/Desktop/list_of_files/5.csv',
 '/home/user/Desktop/list_of_files/1.csv',
 '/home/user/Desktop/list_of_files/3.csv',
 '/home/user/Desktop/list_of_files/2.csv',
 '/home/user/Desktop/list_of_files/4.csv']

输出:

[['File content,5\n'],
 ['File content,1\n'],
 ['File content,3\n'],
 ['File content,2\n'],
 ['File content,4\n']]

【讨论】:

    【解决方案3】:

    您可以使用 csv 模块。这将返回文件夹中每个 csv 的行列表(每一行都是自己的列表),跳过标题:

    # folder/file1.csv
    
    A,B,C,D
    1,foo,bar,null
    42,foo,baz,null
    7,bar,for,x
    
    from os import listdir
    import csv
    
    folder = 'data_folder'
    files = listdir(folder)
    files = [folder + '/' + file for file in files]
    
    files_list = []
    
    for file in files:    
        with open(file) as csv_file: 
            csv_reader = csv.reader(csv_file, delimiter=',')
            
            # skip header
            next(csv_reader, None)
            
            row_list = []
            for row in csv_reader:
                row_list.append(row)
            files_list.append(row_list)
    

    输出:

    [[['1', 'foo', 'bar', 'null'], # file1.csv
      ['42', 'foo', 'baz', 'null'],
      ['7', 'bar', 'for', 'x']],
     [['2', 'foo', 'bar', 'null'], # file2.csv
      ['42', 'foo', 'baz', 'null'],
      ['7', 'bar', 'for', 'x']],
     [['3', 'foo', 'bar', 'null'], # file3.csv
      ['42', 'foo', 'baz', 'null'],
      ['7', 'bar', 'for', 'x']]]
    ...
    

    访问file1.csv中的行:

    file1 = files_list[0]
    print(file1)
    

    输出:

    [['1', 'foo', 'bar', 'null'],
     ['42', 'foo', 'baz', 'null'],
     ['7', 'bar', 'for', 'x']]
    

    【讨论】:

      猜你喜欢
      • 2014-01-21
      • 1970-01-01
      • 1970-01-01
      • 2011-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-10
      • 1970-01-01
      相关资源
      最近更新 更多