简体   繁体   中英

how to copy first 3 lines of all csv files in a folder into one file

Here is a snippet of my current code:

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()

This shows that the file in the location (filepath) now contains one score. I want the program to copy the first 3 lines (3 newest scores) of all csv files in in directory E: and put them in one file.

How would I go about doing this? Swift answers would be greatly appreciated.

There is no need for the csv module when you are dealing with a small part of the data.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM