在python中添加额外的列以输出csv文件

时间:2015-05-22 07:34:15

标签: python csv

我目前在使用某些代码时出现问题,我无法弄清楚如何使用for循环将年份(多个文件名的最后4位数)添加为“ID”字段?我知道还有其他方法可以做到这一点,但我想尝试这种方式,因为我正在学习for循环。

我到目前为止的代码:

import csv

def extract_names(filename):

inF = open(filename, 'rU')
csvF = csv.reader(inFile, delimiter=',')


# Initialization
results = []
rowNum = 0

for row in  csvFile:

    if rowNum != 0:  #no need for first row#

        #This is where the results list is appended #

        records.append((row[0], row[1], "Boy")) 
        records.append((row[2], row[3], "Girl"))  





    rowNum += 1

inF.close()
return(results)



#### Start main program  #####

filenames = ('file2010.csv',     
'file2011.csv',
'file2012.csv', 
'file2013.csv',   
'file2014.csv')

outF = open('fileAll.csv','wb') 
csvF_out = csv.writer(outFile, delimiter=',')

for filename in filenames:
name, ext = filename.split('.')
year = name[-4:]     
results = extract_names(filename)




for line in results:
    line.insert(0,year)

print("Write in csv file...")     

outF.close()

期望的输出:

2010 | Y | X | Z

2 个答案:

答案 0 :(得分:2)

import csv
filenames = (
    'file2010.csv',     
    'file2011.csv',
    'file2012.csv', 
    'file2013.csv',
    'file2014.csv'
)

outF = open('fileAll.csv', 'wb') 
csvF_out = csv.writer(outF, delimiter=',')

def extract_content(filename):
    return [("0","1","boy"),("2","3","girl")]

for filename in filenames:
    name, ext = filename.split('.')
    year = name[-4:]     
    result = extract_content(filename)
    for row in result:
        csvF_out.writerow((year,)+row)

outF.close()


#  fileall.csv:
# 2010  | x |   y | z
# 2011  | x |   y | z
# 2012  | x |   y | z
# 2013  | x |   y | z
# 2014  | x |   y | z

其中|代表一个新专栏。 请注意,代码不是在循环外使用csv.writerows,而是在for循环中使用csv.writerow。不需要额外的循环。

答案 1 :(得分:0)

你想插入年份作为每一行的第一个单元格(如果我理解正确。如果认为以下是自我解释

filenames = ('file2010.csv',
             'file2011.csv',
             'file2012.csv',
             'file2013.csv',
             'file2014.csv')

outF = open('fileAll.csv','wb')
csvF_out = csv.writer(outF, delimiter=',')

for filename in filenames:
    name, ext = filename.split('.')
    year = name[-4:]
    result = extract_content(filename)

    ### Here is the loop you are looking for
    for line in result:      # for each line
        line.insert(0, year) # insert the year as the first cell

    csvF_out.writerows(reult)

outF.close()

很少有其他笔记

  • 查看更安全的with open(file):
  • 您期望2010 | Y | X | Z,而您的分隔符在您的作者中设为,