#-----------single csv lines------------- import csv header = ['name', 'area', 'country_code2', 'country_code3'] data = ['Afghanistan', 652090, 'AF', 'AFG'] with open('countries-1.csv', 'w', encoding='UTF8', newline='') as f: writer = csv.writer(f) writer.writerow(header) writer.writerow(data) |
The content of countries-1.csv: |
#-----------multiple csv lines------------- import csv header = ['name', 'area', 'country_code2', 'country_code3'] data = [ ['Albania', 28748, 'AL', 'ALB'], ['Algeria', 2381741, 'DZ', 'DZA'], ['American Samoa', 199, 'AS', 'ASM'], ['Andorra', 468, 'AD', 'AND'], ['Angola', 1246700, 'AO', 'AGO'] ] with open('countries-2.csv', 'w', encoding='UTF8', newline='') as f: writer = csv.writer(f) writer.writerow(header) writer.writerows(data) |
The content of countries-2.csv: |
print('\ncsv read-1....basic') import csv with open('stud.csv', 'r') as f: csv_reader = csv.reader(f) for line in csv_reader: print(line) print('\ncsv read-2....next() to skip header') import csv with open('stud.csv', encoding="utf8") as f: csv_reader = csv.reader(f) next(csv_reader) for line in csv_reader: print(line) print('\ncsv read-3....use enumerate to put number on each line') import csv with open('stud.csv', encoding="utf8") as f: csv_reader = csv.reader(f) for line_no, line in enumerate(csv_reader): if line_no == 0: print('Header:') print(line) # header print('Data:') else: print(line_no,line) # data |
tthe initial position and speed : 0 , 2 the position and speed at t= 1 x= 6.9 v= 11.8 |
print('\ncsv read-3....use enumerate to put number on each line') import csv with open('stud.csv', encoding="utf8") as f: csv_reader = csv.reader(f) for line_no, line in enumerate(csv_reader): if line_no == 0: print('Header:') print(line) # header print('Data:') else: print(line_no,line) # data w=open('stud-2.csv', 'w') writer = csv.writer(w) with open('stud.csv', encoding="utf8") as f: csv_reader = csv.reader(f) for line_no, line in enumerate(csv_reader): if line_no == 0: writer.writerow(line) else: line[1]='xxx' writer.writerow(line) w.close() print('end of py') |
the content of stud-2.csv: |