代码实现
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# 执行方式:python3 parse_csv.py
import csv
def write_csv():
row0 = ['name', 'university', 'gender', 'score']
row1 = ['Jesse', 'HIT', 'man', 99]
row2 = ['White', 'MIT', 'woman', 98]
row3 = ['Snow', 'UCLA', 'man', 97]
total_row = [row0, row1, row2, row3]
# https://blog.csdn.net/qq_38463737/article/details/107400208
# 每次读写之时都要删除之前的内容,使用'w+'
# 每次读写文件都是在文件末尾增添内容,使用'a+'
with open('student.csv', 'w+') as csv_file:
writer = csv.writer(csv_file)
for row in total_row:
writer.writerow(row)
def read_csv():
with open('student.csv', 'r') as csv_file:
reader = csv.reader(csv_file)
line_count = 0
for row in reader:
if(line_count == 0):
print(f'{row[0]}\t{row[1]}\t{row[2]}\t{row[3]}')
line_count += 1
else:
print(f'{row[0]}\t{row[1]}\t\t{row[2]}\t{row[3]}')
line_count += 1
def main():
write_csv()
read_csv()
if __name__ == '__main__':
main()
student.csv
name,university,gender,score
Jesse,HIT,man,99
White,MIT,woman,98
Snow,UCLA,man,97