Dalam tutorial ini, kita akan belajar membaca dan menulis ke dalam fail CSV di Python dengan bantuan contoh.
Format CSV (Comma Separated Value) adalah salah satu cara paling mudah dan biasa untuk menyimpan data jadual. Untuk mewakili fail CSV, fail mesti disimpan dengan sambungan fail .csv .
Mari kita ambil contoh:
Sekiranya anda membuka fail CSV di atas menggunakan penyunting teks seperti teks luhur, anda akan melihat:
SN, Nama, Bandar 1, Michael, New Jersey 2, Jack, California
Seperti yang anda lihat, elemen-elemen fail CSV dipisahkan dengan koma. Di sini, ,
adalah pembatas.
Anda boleh mempunyai watak tunggal sebagai pembatas mengikut keperluan anda.
Catatan: Modul csv juga dapat digunakan untuk sambungan fail lain (seperti: .txt ) selagi kandungannya dalam struktur yang betul.
Bekerja dengan fail CSV di Python
Walaupun kita dapat menggunakan open()
fungsi bawaan untuk bekerja dengan file CSV di Python, ada csv
modul khusus yang membuat kerja dengan fail CSV menjadi lebih mudah.
Sebelum kita dapat menggunakan kaedah ke csv
modul, kita perlu mengimport modul terlebih dahulu dengan menggunakan:
import csv
Membaca fail CSV Menggunakan csv.reader ()
Untuk membaca fail CSV di Python, kita dapat menggunakan csv.reader()
fungsinya. Misalkan kita mempunyai csv
fail bernama people.csv dalam direktori semasa dengan entri berikut.
Nama | Umur | Profesion |
Jack | 23 | Doktor |
Miller | 22 | Jurutera |
Mari baca fail ini dengan menggunakan csv.reader()
:
Contoh 1: Baca CSV Mempunyai Pemisah Koma
import csv with open('people.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row)
Pengeluaran
('Nama', 'Umur', 'Profesi') ('Jack', '23', 'Doktor') ('Miller', '22', 'Jurutera')
Di sini, kami telah membuka fail People.csv dalam mod membaca menggunakan:
with open('people.csv', 'r') as file:…
Untuk mengetahui lebih lanjut mengenai membuka fail di Python, lawati: Python File Input / Output
Kemudian, csv.reader()
digunakan untuk membaca fail, yang mengembalikan reader
objek yang dapat diulang .
The reader
objek kemudiannya mengulangi menggunakan for
gelung untuk mencetak kandungan setiap baris.
Dalam contoh di atas, kami menggunakan csv.reader()
fungsi dalam mod lalai untuk fail CSV yang mempunyai pembatas koma.
Walau bagaimanapun, fungsinya jauh lebih disesuaikan.
Katakan fail CSV kami menggunakan tab sebagai pembatas. Untuk membaca fail tersebut, kita dapat meneruskan parameter pilihan ke csv.reader()
fungsi tersebut. Mari kita ambil contoh.
Contoh 2: Baca fail CSV Mempunyai Tab Delimiter
import csv with open('people.csv', 'r',) as file: reader = csv.reader(file, delimiter = ' ') for row in reader: print(row)
Perhatikan parameter pilihan delimiter = ' '
dalam contoh di atas.
Sintaks lengkap csv.reader()
fungsi adalah:
csv.reader(csvfile, dialect='excel', **optional_parameters)
Seperti yang anda lihat dari sintaks, kita juga dapat meneruskan parameter dialek ke csv.reader()
fungsi. The dialect
parameter membolehkan kita untuk membuat fungsi yang lebih fleksibel. Untuk mengetahui lebih lanjut, lawati: Membaca fail CSV di Python.
Menulis fail CSV Menggunakan csv.writer ()
Untuk menulis ke fail CSV di Python, kita dapat menggunakan csv.writer()
fungsi tersebut.
Yang csv.writer()
mengembalikan writer
objek yang mualaf data pengguna ke dalam rentetan yang dibatasi. Rentetan ini kemudian dapat digunakan untuk menulis ke dalam file CSV menggunakan writerow()
fungsi tersebut. Mari kita ambil contoh.
Contoh 3: Tulis ke fail CSV
import csv with open('protagonist.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerow(("SN", "Movie", "Protagonist")) writer.writerow((1, "Lord of the Rings", "Frodo Baggins")) writer.writerow((2, "Harry Potter", "Harry Potter"))
Semasa kita menjalankan program di atas, file protagonist.csv dibuat dengan kandungan berikut:
SN, Filem, Protagonis 1, Lord of the Rings, Frodo Baggins 2, Harry Potter, Harry Potter
Dalam program di atas, kami telah membuka fail dalam mod penulisan.
Kemudian, kami telah melewati setiap baris sebagai senarai. Senarai ini ditukar menjadi rentetan yang dipisahkan dan ditulis ke dalam fail CSV.
Contoh 4: Menulis berbilang baris dengan penulis baris ()
Sekiranya kita perlu menulis kandungan senarai 2 dimensi ke fail CSV, inilah cara kita dapat melakukannya.
import csv csv_rowlist = (("SN", "Movie", "Protagonist"), (1, "Lord of the Rings", "Frodo Baggins"), (2, "Harry Potter", "Harry Potter")) with open('protagonist.csv', 'w') as file: writer = csv.writer(file) writer.writerows(csv_rowlist)
The output of the program is the same as in Example 3.
Here, our 2-dimensional list is passed to the writer.writerows()
method to write the content of the list to the CSV file.
Example 5: Writing to a CSV File with Tab Delimiter
import csv with open('protagonist.csv', 'w') as file: writer = csv.writer(file, delimiter = ' ') writer.writerow(("SN", "Movie", "Protagonist")) writer.writerow((1, "Lord of the Rings", "Frodo Baggins")) writer.writerow((2, "Harry Potter", "Harry Potter"))
Notice the optional parameter delimiter = ' '
in the csv.writer()
function.
The complete syntax of the csv.writer()
function is:
csv.writer(csvfile, dialect='excel', **optional_parameters)
Similar to csv.reader()
, you can also pass dialect parameter the csv.writer()
function to make the function much more customizable. To learn more, visit: Writing CSV files in Python
Python csv.DictReader() Class
The objects of a csv.DictReader()
class can be used to read a CSV file as a dictionary.
Example 6: Python csv.DictReader()
Suppose we have the same file people.csv as in Example 1.
Name | Age | Profession |
Jack | 23 | Doctor |
Miller | 22 | Engineer |
Let's see how csv.DictReader()
can be used.
import csv with open("people.csv", 'r') as file: csv_file = csv.DictReader(file) for row in csv_file: print(dict(row))
Output
('Name': 'Jack', ' Age': ' 23', ' Profession': ' Doctor') ('Name': 'Miller', ' Age': ' 22', ' Profession': ' Engineer')
As we can see, the entries of the first row are the dictionary keys. And, the entries in the other rows are the dictionary values.
Here, csv_file is a csv.DictReader()
object. The object can be iterated over using a for
loop. The csv.DictReader()
returned an OrderedDict
type for each row. That's why we used dict()
to convert each row to a dictionary.
Notice that, we have explicitly used the dict() method to create dictionaries inside the for
loop.
print(dict(row))
Note: Starting from Python 3.8, csv.DictReader() returns a dictionary for each row, and we do not need to use dict()
explicitly.
The full syntax of the csv.DictReader()
class is:
csv.DictReader(file, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)
To learn more about it in detail, visit: Python csv.DictReader() class
Python csv.DictWriter() Class
The objects of csv.DictWriter()
class can be used to write to a CSV file from a Python dictionary.
The minimal syntax of the csv.DictWriter()
class is:
csv.DictWriter(file, fieldnames)
Here,
file
- CSV file where we want to write tofieldnames
- alist
object which should contain the column headers specifying the order in which data should be written in the CSV file
Example 7: Python csv.DictWriter()
import csv with open('players.csv', 'w', newline='') as file: fieldnames = ('player_name', 'fide_rating') writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writeheader() writer.writerow(('player_name': 'Magnus Carlsen', 'fide_rating': 2870)) writer.writerow(('player_name': 'Fabiano Caruana', 'fide_rating': 2822)) writer.writerow(('player_name': 'Ding Liren', 'fide_rating': 2801))
The program creates a players.csv file with the following entries:
player_name,fide_rating Magnus Carlsen,2870 Fabiano Caruana,2822 Ding Liren,2801
The full syntax of the csv.DictWriter()
class is:
csv.DictWriter(f, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)
To learn more about it in detail, visit: Python csv.DictWriter() class
Using the Pandas library to Handle CSV files
Pandas is a popular data science library in Python for data manipulation and analysis. If we are working with huge chunks of data, it's better to use pandas to handle CSV files for ease and efficiency.
Before we can use pandas, we need to install it. To learn more, visit: How to install Pandas?
Once we install it, we can import Pandas as:
import pandas as pd
To read the CSV file using pandas, we can use the read_csv()
function.
import pandas as pd pd.read_csv("people.csv")
Di sini, program membaca People.csv dari direktori semasa.
Untuk menulis ke fail CSV, kita perlu memanggil to_csv()
fungsi DataFrame.
import pandas as pd # creating a data frame df = pd.DataFrame((('Jack', 24), ('Rose', 22)), columns = ('Name', 'Age')) # writing data frame to a CSV file df.to_csv('person.csv')
Di sini, kami telah membuat DataFrame menggunakan pd.DataFrame()
kaedah. Kemudian, to_csv()
fungsi untuk objek ini dipanggil, untuk menulis ke person.csv .
Untuk mengetahui lebih lanjut, lawati:
- Python pandas.read_csv (laman rasmi)
- Python pandas.pandas.DataFrame.to_csv (laman rasmi)