Untuk membaca data daripada fail CSV, gunakan perpustakaan CSV Python. Berikut ialah contoh:
import csv # Open the CSV file for reading with open("test.csv", "rt") as f: # Create a CSV reader object reader = csv.reader(f, delimiter=",", quotechar='"') # Iterate over the rows in the CSV file for row in reader: print(row)
Untuk menulis data pada fail CSV, gunakan juga perpustakaan CSV Python:
import csv # Create a list of data to write to the CSV file data = [ (1, "A towel", 1.0), (42, " it says, ", 2.0), (1337, "is about the most ", -1), (0, "massively useful thing ", 123), (-2, "an interstellar hitchhiker can have.", 3), ] # Open the CSV file for writing with open("test.csv", "wt") as f: # Create a CSV writer object writer = csv.writer(f, delimiter=",", quotechar='"') # Write the data to the CSV file writer.writerows(data)
Apabila bekerja dengan fail CSV:
Berikut ialah output contoh kod:
1,"A towel,",1.0 42," it says, ",2.0 1337,is about the most ,-1 0,massively useful thing ,123 -2,an interstellar hitchhiker can have.,3
Atas ialah kandungan terperinci Bagaimana untuk Membaca dan Menulis Fail CSV dalam Python?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!