如何将文件夹中所有csv文件的前3行复制到一个fi中

2024-10-04 05:32:17 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我当前代码的一个片段:

with open((filepath), 'w') as t:
    data = [(name), "scored", (str(score)) + "/10"]
    preader = csv.reader(t, delimiter=' ', quotechar='|')
    pwriter = csv.writer(t, delimiter=' ', quotechar='|',          quoting=csv.QUOTE_MINIMAL)
pwriter.writerow(data)
t.close()

这表明位置(filepath)中的文件现在包含一个分数。 我想让程序复制的前3行(3个最新的分数)的所有csv文件在目录E:和把他们放在一个文件。你知道吗

我该怎么做呢?如能迅速答复,将不胜感激。你知道吗


Tags: 文件csv代码namedataaswithopen
1条回答
网友
1楼 · 发布于 2024-10-04 05:32:17

在处理一小部分数据时,不需要csv模块。你知道吗

import os
items_in_directory = os.listdir("E:/")
csv_files = [x for x in items_in_directory if x.endswith(".csv")]
# File to write to
f = open("file_out.txt", "a")

for csv_file in csv_files:
    with open(csv_file) as csv:
        for i, line in enumerate(csv):
            f.write(line.strip("\n"))
            if i == 2:
                f.write("\n")
                break

相关问题 更多 >