讀寫CSV 檔案
第三方庫CSV中提供了2個類來寫CSV檔案
- csv.writer class
csv.writer class provides two methods for writing to CSV. They are writerow() and writerows().
writerow(): This method writes a single row at a time. Field row can be written using this method.
Syntax:
writerow(fields)
writerows(): This method is used to write multiple rows at a time. This can be used to write rows list.
Syntax:
Writing CSV files in Python
writerows(rows)
- csv.DictWriter class
csv.DictWriter provides two methods for writing to CSV. They are:
writeheader(): writeheader() method simply writes the first row of your csv file using the pre-specified fieldnames.
Syntax:
writeheader()
writerows(): writerows method simply writes all the rows but in each row, it writes only the values(not keys).
Syntax:
writerows()
同樣,在讀CSV檔案時,也可以用 csv.DictReader() class和csv.reader()來讀
import csv def WriterCSV(): fields = ['Name', 'Branch', 'Year', 'CGPA'] rows = [['Nikhil', 'COE', '2', '9.0'], ['Sanchit', 'COE', '2', '9.1'], ['Aditya', 'IT', '2', '9.3'], ['Sagar', 'SE', '1', '9.5'], ['Prateek', 'MCE', '3', '7.8'], ['Sahil', 'EP', '2', '9.1']] filename = "test1.csv" with open(filename, 'w', newline='') as csvfile: # 在以這種方法寫CSV時,需要加newline='',否則讀CSV時,會有多個空列表,原因待確定 # creating a csv writer object csvwriter = csv.writer(csvfile) # writing the fields csvwriter.writerow(fields) # writing the data rows csvwriter.writerows(rows) def writerSCVDict(): mydict = [{'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year': '2'}, {'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit', 'year': '2'}, {'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya', 'year': '2'}, {'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar', 'year': '1'}, {'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek', 'year': '3'}, {'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil', 'year': '2'}] fields = ['name', 'branch', 'year', 'cgpa'] filename = "test2.csv" with open(filename, 'w') as csvfile: # creating a csv dict writer object writer = csv.DictWriter(csvfile, fieldnames=fields) # writing headers (field names) writer.writeheader() # writing data rows writer.writerows(mydict) def ReadingCSV(): import csv # opening the CSV file with open('test1.csv', mode='r')as file: # reading the CSV file csvFile = csv.reader(file) # displaying the contents of the CSV file for lines in csvFile: # if lines != '\n': print(lines) def DictReaderCSV(): import csv # opening the CSV file with open('test2.csv', mode='r') as file: # reading the CSV file csvFile = csv.DictReader(file) # displaying the contents of the CSV file for lines in csvFile: print(lines)
參考部落格:
https://www.geeksforgeeks.org/reading-csv-files-in-python/?ref=lbp
https://www.geeksforgeeks.org/writing-csv-files-in-python/?ref=lbp