Read multiple csv data files and sort into a new csv file

Hello,

I am trying to read through multiple csv files in a folder, extract three lines from each csv file and write these information in a new csv file. I am able to get the “for” loop running without write the result into the csv files. But with the code below, the new csv file (“sort.csv”) only contain the header of the data strings without the real data.

my code:

import os
import glob
import csv
#path contain the directory of the folder
path = r'C:\Users\Time estimates task\modified psychopy\reading data-2'
extension = 'csv'
os.chdir(path)
csvlist = glob.glob('*.{}'.format(extension))
print(csvlist) #print out the list of csv file names
for file in csvlist:
    with open (file,'r') as csvfile:
        csv_reader=csv.DictReader(csvfile)
#        for line in csv_reader:
#            print (line['participant'])
        with open('sort.csv','w') as sortfile:
            fieldnames=['key_resp.rt','key_resp_4.rt', 'participant']
            csv_writer=csv.DictWriter(sortfile,fieldnames=fieldnames,delimiter=',',extrasaction='ignore')
            csv_writer.writeheader()
            for line in csv_reader:
                csv_writer.writerow(line)