Python从csv读取数据并将数据写入csv

时间:2014-05-18 13:43:12

标签: python csv

我需要从预定义的目录中读取每个csv文件,对于该目录中的每个csv,我需要占用每一行并将其写入新的csv文件。 目前,我有这个代码片段,它读取特定的csv文件并在每一行上循环。

import csv
with open('E:\EE\EE\TocsData\CSAT\csat_20140331.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=',', quotechar='|')
    for row in reader:
        # write row to a seperate csv file

2 个答案:

答案 0 :(得分:0)

类似的东西应该有用。遍历目录中的所有文件,从每个文件中读取并将所有行写入新文件。

    myDirectory = "E:\EE\EE\TocsData\CSAT\\"
    myNewCSV= "E:\myNewCSV.csv"
    with open(myNewCSV,'ab') as w:  #append bytes:'ab', write bytes:'wb' - whichever you want.
        for myFile in os.listdir(myDirectory):
            absolutePath = myDirectory + str(myFile)
            writer = csv.writer(w)
            with open(absolutePath, 'rb') as r:
                 reader = csv.reader(r)
                 for row in reader:
                     writer.writerow(row)

答案 1 :(得分:0)

试试这个:

import glob
import csv

with open('somefile.out', 'wb') as out:
    writer = csv.writer(out, delimiter=',')
    for inf in glob.glob(r'E:\EE\EE\TocsData\CSAT\*.csv'):
        with open(inf, 'rb') as csv_input:
            reader = csv.reader(csv_input, delimiter=',', quotechar='|')
            for row in reader:
                writer.write(row)