import csv
TEST_FILE = "textFiles/csvTestFile.csv"
print("**********第一种方式")
with open(TEST_FILE) as csvFile:
CSV_FILE = csv.reader(csvFile)
for ROW in CSV_FILE:
print(ROW)
print("**********第二种方式")
def open_and_print(file_path):
with open(file_path) as csvFile:
dict_csv = csv.DictReader(csvFile)
for row in dict_csv:
for key, value in row.items():
print("%s:%s" % (key,value), end='\t\t\t')
print("")
return
open_and_print(TEST_FILE)
print("**********写入CSV文件")
def save_csv(file_path, header, rows):
with open(file_path, 'w') as f_to_save:
f_csv = csv.writer(f_to_save, lineterminator='\n')
f_csv.writerow(headers)
f_csv.writerows(rows)
return
headers = ['Symbol','Price','Date','Time','Change','Volume']
rows = [('AA', 39.48, '6/11/2007', '9:36am', -0.18, 181800),
('AIG', 71.38, '6/11/2007', '9:36am', -0.15, 195500),
('AXP', 62.58, '6/11/2007', '9:36am', -0.46, 935000),
]
save_csv('textFiles/stocks.csv', headers, rows)
open_and_print('textFiles/stocks.csv')