我的任务是制作一个程序,该程序使用CSV文件中的信息并提取学生入学的年份,名字的前三个字母和姓的前两个字母。
这是我当前的代码:
names = []
with open('Spreadsheet2.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for row in readCSV:
names.append(row)
print(names)
示例输出为:
`[['John', 'Doe', '2018'], ['Edward', 'Kaizak', '2014'],
['Elizabeth', 'Dezir', '2013'], ['Jack', 'Wilder', '2014'],
['Lily', 'Rais', '2015'], ['Ken', 'Lowley', '2015'],
['Edna', 'Bores', '2015'], ['Jacqueline', 'Keis', '2016'],
['Tammy', 'Howst', '2017']]`
我需要将提取的数据写入新的CSV文件。
感谢您的帮助。
答案 0 :(得分:0)
在这里
import csv
new_rows = []
with open('in1.csv', 'r') as f_in:
reader = csv.reader(f_in, delimiter=',')
for row in reader:
new_rows.append([row[0][:3], row[1][:2], row[2]])
with open('out.csv', 'w',newline='') as f_out:
writer = csv.writer(f_out, delimiter=',')
writer.writerows(new_rows)
输入文件:
John,Doe,2018
Jack,Smith,2017
输出文件:
Joh,Do,2018
Jac,Sm,2017
答案 1 :(得分:0)
如果您的问题是生成数据,则应查看python的索引运算符。
my_string = "hello there"
# first 3 characters
my_string[:3] # 'hel'
# last 5 characters
my_string[-5:] # 'there'
# from 3rd to 5th characters
my_string[3:5] # 'lo'
# last character
my_string[-1] # 'e'
# etc...
干杯!