gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:42:06 25 4
gpt4 key购买 nike

我目前在某些代码方面遇到了麻烦,我不太清楚如何使用 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

最佳答案

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。不需要额外的循环。

关于python - 在 python 中添加额外的列以输出 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30390896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com