[英]How can i read the maximum amount of lines in a csv file?
我有一个 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)
但它似乎不起作用。 我想上传一些文件作为示例,但我不知道。 如果有人知道我会很乐意这样做
您可以预处理您的文件,以填充少于最大列数的行。 参考: Python csv; 获取所有列的最大长度,然后将所有其他列延长到该长度
您还可以使用 sep 参数,或者,如果它无法正确读取您的 CSV,则将文件读取为固定宽度。 查看这个问题的答案: Read CSV into a dataFrame with different row length using Pandas
看起来你实际上有两个问题:
获取所有文件中所有列的完整列表
从每个文件中读取最后一行并合并到正确的列中
为了解决这个问题,标准的 Python csv
模块比 Pandas 更有意义。
我假设你已经确定了你需要的文件列表,它在你的files
变量中
首先获取所有标题
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)
现在读取最后几行并将它们写入结果文件
使用DictReader
和DictWriter
提供映射到标题的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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.