|
| 1 | +import csv |
| 2 | + |
| 3 | + |
| 4 | +def read_csv(filename): |
| 5 | + file_instance = open(filename, encoding="UTF8") |
| 6 | + |
| 7 | + csv_reader = csv.reader(file_instance) |
| 8 | + |
| 9 | + for line in csv_reader: |
| 10 | + print(line) |
| 11 | + |
| 12 | + file_instance.close() |
| 13 | + |
| 14 | + |
| 15 | +def write_csv(filename): |
| 16 | + file_instance = open(filename, "w", encoding="UTF8") |
| 17 | + |
| 18 | + csv_writer = csv.writer(file_instance) |
| 19 | + |
| 20 | + header = ['Name', 'Chinese', 'English', 'Math'] |
| 21 | + rows = [ |
| 22 | + ['Zhangsan', '80', '87', '100'], |
| 23 | + ['Lisi', '78', '79', '98'], |
| 24 | + ['Wangwu', '67', '90', '88'] |
| 25 | + ] |
| 26 | + |
| 27 | + csv_writer.writerow(header) |
| 28 | + csv_writer.writerows(rows) |
| 29 | + |
| 30 | + file_instance.close() |
| 31 | + |
| 32 | + |
| 33 | +def dict_write_csv(filename): |
| 34 | + file_instance = open(filename, "w", encoding="UTF8") |
| 35 | + |
| 36 | + header = ['name', 'chinese', 'english', 'math'] |
| 37 | + |
| 38 | + csv_writer = csv.DictWriter(file_instance, header) |
| 39 | + rows = [ |
| 40 | + {"name": 'Zhangsan', |
| 41 | + "chinese": '80', |
| 42 | + "english": '87', |
| 43 | + "math": '100'}, |
| 44 | + {"name": 'Lisi', |
| 45 | + "chinese": '76', |
| 46 | + "english": '80', |
| 47 | + "math": '98'}, |
| 48 | + {"name": 'Wangwu', |
| 49 | + "chinese": '60', |
| 50 | + "english": '77', |
| 51 | + "math": '90'} |
| 52 | + ] |
| 53 | + |
| 54 | + csv_writer.writeheader() |
| 55 | + csv_writer.writerows(rows) |
| 56 | + |
| 57 | + file_instance.close() |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == '__main__': |
| 61 | + filename = "students3.csv" |
| 62 | + |
| 63 | + # write_csv(filename) |
| 64 | + dict_write_csv(filename) |
| 65 | + read_csv(filename) |
0 commit comments