【问题标题】:How can i read the maximum amount of lines in a csv file?如何读取 csv 文件中的最大行数?
【发布时间】:2019-12-07 17:12:00
【问题描述】:

我有一个 python 脚本,它读取一堆 csv 文件并创建一个新的 csv 文件,其中包含读取的每个文件的最后一行。脚本是这样的:

    import pandas as pd
    import glob
    import os

    path = r'Directory of the files read\*common_file_name_part.csv'
    r_path = r'Directory where the resulting file is saved.'
    if os.path.exists(r_path + 'csv'):
       os.remove(r_path + 'csv')
    if os.path.exists(r_path + 'txt'):
       os.remove(r_path + 'txt')

    files = glob.glob(path)
    column_list = [None] * 44
    for i in range(44):
        column_list[i] = str(i + 1)

    df = pd.DataFrame(columns = column_list)
    for name in files:
        df_n = pd.read_csv(name, names = column_list)
        df = df.append(df_n.iloc[-1], ignore_index=True)
        del df_n

    df.to_csv(r_path + 'csv', index=False, header=False)
    del df

这些文件都有一个共同的名字结尾和一个真正的名字开头。结果文件没有扩展名,所以我可以做一些检查。 我的问题是文件的行数和列数不定,即使在同一个文件中,我也无法正确读取它们。如果我不指定列名,程序会假定第一行作为列名,这会导致某些文件中丢失很多列。另外,我尝试通过以下方式读取没有标题的文件:

    df = pd.read_csv(r_path, header=None)

但它似乎不起作用。 我想上传一些文件作为示例,但我不知道。如果有人知道我会很乐意这样做

【问题讨论】:

  • 您是否有理由需要使用 pandas?你真的只对每个 csv 文件的最后一行感兴趣吗?
  • 是的。我只想要每个文件的最后一行。
  • 那么你应该能够在没有熊猫的情况下做到这一点。谷歌搜索get last line of file in python 应该会给你很多更好的方法
  • Pandas 是我发现读取 csv 的唯一方法,因为其他所有方法都会删除分隔符,这是我不想要的。可能还有更多可用的,但不幸的是我没有找到它们。
  • @GeorgeTsaki CSV 文件只是文本。行是一个字符串,只需将其写入文件即可。你可以用几行 Python 完成所有的 pandas 代码。

标签: python pandas dataframe


【解决方案1】:

您可以对文件进行预处理,以填充列数少于最大列数的行。 参考:Python csv; get max length of all columns then lengthen all other columns to that length

您也可以使用 sep 参数,或者,如果它无法正确读取您的 CSV,则以固定宽度读取文件。查看这个 SO 问题的答案:Read CSV into a dataFrame with varying row lengths using Pandas

【讨论】:

  • 或者不能使用 pandas,因为他不关心 csv 文件中的任何数据,只对将每个文件的最后一行写入单个文件感兴趣。
  • 是的,我认为如果没有任何数据操作会更好!他可以使用内置的 csv 模块来代替
【解决方案2】:

看起来你实际上有两个问题:

  1. 获取所有文件中所有列的完整列表

  2. 读取每个文件的最后一行并合并到正确的列中

为了解决这个问题,标准 Python csv 模块比 Pandas 更有意义。

我假设你已经确定了你需要的文件列表,它在你的 files 变量中

先获取所有的header

import csv

# Use a set to eliminate eleminate duplicates
headers = set()

# Read the header from each file
for file in files:
    with open(file) as f:
        reader = csv.reader(f)

        # Read the first line as this will be the header
        header = next(reader)

        # Update the set with the list of headers
        headers.update(header)

print("Headers:", headers)

现在读取最后几行并将它们写入结果文件

使用DictReaderDictWriter 提供映射到标头的dict

with open(r_path, "w") as f_out:
    # The option extrasaction="ignore" allows for not
    # all columns to be provided when calling writerow
    writer = DictWriter(f_out, fieldnames=headers, extrasaction="ignore")
    writer.writeheader()

    # Read the last line of each file
    for file in files:
        with open(file) as f_in:
            reader = csv.DictReader(f_in)

            # Read all and ignore only keep the last line
            for row in reader: 
                pass

            # Write the last row into the result file
            writer.writerow(row)

【讨论】:

  • 我收到一个错误,我缺少 DictWriter 中的字段名参数。由于我不熟悉 dictwriter,我应该把什么作为字段名?
  • 更新了参数,显然无法测试,因为我没有一大堆 CSV 文件 ;)
  • 现在它说它缺少 f 位置参数而实际上没有丢失它。
  • csv.DictReader(f_in) 需要文件句柄。
  • 现在我测试了代码,看起来它生成了一个非常混乱的文件。单元格的顺序发生了变化,有些行在单元格之间有很多空格,并且在行之间也有空格。最后,第一行似乎是它应该大小的三倍
猜你喜欢
  • 2021-03-18
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-11
  • 2022-09-23
  • 1970-01-01
  • 2013-04-30
相关资源
最近更新 更多