Dalam tutorial ini, kita akan belajar membaca file CSV dengan format berbeda dengan Python dengan bantuan contoh.
Kami akan secara eksklusif menggunakan csv
modul yang dibangun ke dalam Python untuk tugas ini. Tapi pertama-tama, kita harus mengimpor modul sebagai:
import csv
Kami telah membahas dasar-dasar cara menggunakan csv
modul untuk membaca dan menulis ke dalam file CSV. Jika Anda tidak tahu cara menggunakan csv
modul ini, lihat tutorial kami tentang CSV Python: Membaca dan Menulis file CSV
Penggunaan Dasar csv.reader ()
Mari kita lihat contoh dasar penggunaan csv.reader()
untuk menyegarkan pengetahuan Anda yang sudah ada.
Contoh 1: Membaca file CSV dengan csv.reader ()
Misalkan kita memiliki file CSV dengan entri berikut:
SN, Nama, Kontribusi 1, Linus Torvalds, Linux Kernel 2, Tim Berners-Lee, World Wide Web 3, Guido van Rossum, Pemrograman Python
Kita bisa membaca isi file dengan program berikut:
import csv with open('innovators.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row)
Keluaran
('SN', 'Name', 'Contribution') ('1', 'Linus Torvalds', 'Linux Kernel') ('2', 'Tim Berners-Lee', 'World Wide Web') ('3' , 'Guido van Rossum', 'Pemrograman Python')
Di sini, kami telah membuka file inovators.csv dalam mode membaca menggunakan open()
fungsi.
Untuk mempelajari lebih lanjut tentang membuka file dengan Python, kunjungi: Python File Input / Output
Kemudian, csv.reader()
digunakan untuk membaca file, yang mengembalikan reader
objek yang dapat diulang .
The reader
objek kemudian mengulangi menggunakan for
loop untuk mencetak isi dari setiap baris.
Sekarang, kita akan melihat file CSV dengan format berbeda. Kami kemudian akan belajar bagaimana menyesuaikan csv.reader()
fungsi untuk membacanya.
File CSV dengan Pembatas Kustom
Secara default, koma digunakan sebagai pembatas di file CSV. Namun, beberapa file CSV dapat menggunakan pembatas selain koma. Beberapa yang populer adalah |
dan
.
Misalkan file inovators.csv pada Contoh 1 menggunakan tab sebagai pembatas. Untuk membaca file tersebut, kita dapat mengirimkan delimiter
parameter tambahan ke csv.reader()
fungsi tersebut.
Mari kita ambil contoh.
Contoh 2: Membaca file CSV yang Memiliki Tab Delimiter
import csv with open('innovators.csv', 'r') as file: reader = csv.reader(file, delimiter = ' ') for row in reader: print(row)
Keluaran
('SN', 'Name', 'Contribution') ('1', 'Linus Torvalds', 'Linux Kernel') ('2', 'Tim Berners-Lee', 'World Wide Web') ('3' , 'Guido van Rossum', 'Pemrograman Python')
Seperti yang bisa kita lihat, parameter opsional delimiter = ' '
membantu menentukan reader
objek dari file CSV yang kita baca, memiliki tab sebagai pembatas.
File CSV dengan spasi awal
Beberapa file CSV dapat memiliki karakter spasi setelah pembatas. Saat kami menggunakan csv.reader()
fungsi default untuk membaca file CSV ini, kami juga akan mendapatkan spasi di output.
Untuk menghapus spasi awal ini, kita perlu meneruskan parameter tambahan yang disebut skipinitialspace
. Mari kita lihat contohnya:
Contoh 3: Membaca file CSV dengan spasi awal
Misalkan kita memiliki file CSV bernama people.csv dengan konten berikut:
SN, Nama, Kota 1, John, Washington 2, Eric, Los Angeles 3, Brad, Texas
Kita bisa membaca file CSV sebagai berikut:
import csv with open('people.csv', 'r') as csvfile: reader = csv.reader(csvfile, skipinitialspace=True) for row in reader: print(row)
Keluaran
('SN', 'Name', 'City') ('1', 'John', 'Washington') ('2', 'Eric', 'Los Angeles') ('3', 'Brad', ' Texas ')
Program ini mirip dengan contoh lain tetapi memiliki skipinitialspace
parameter tambahan yang disetel ke True.
Ini memungkinkan reader
objek mengetahui bahwa entri memiliki spasi awal. Akibatnya, spasi awal yang ada setelah pembatas dihapus.
File CSV dengan tanda kutip
Beberapa file CSV dapat memiliki tanda kutip di setiap atau beberapa entri.
Mari kita ambil quotes.csv sebagai contoh, dengan entri berikut:
"SN", "Nama", "Kutipan" 1, Buddha, "Kami pikir kita akan menjadi" 2, Mark Twain, "Jangan pernah menyesali apa pun yang membuatmu tersenyum" 3, Oscar Wilde, "Jadilah dirimu sendiri, semua orang sudah diambil"
Menggunakan csv.reader()
dalam mode minimal akan menghasilkan keluaran dengan tanda kutip.
Untuk menghapusnya, kita harus menggunakan parameter opsional lain yang disebut quoting
.
Mari kita lihat contoh cara membaca program di atas.
Contoh 4: Membaca file CSV dengan tanda kutip
import csv with open('person1.csv', 'r') as file: reader = csv.reader(file, quoting=csv.QUOTE_ALL, skipinitialspace=True) for row in reader: print(row)
Keluaran
('SN', 'Name', 'Quotes') ('1', 'Buddha', 'What we think we become') ('2', 'Mark Twain', 'Never regret anything that made you smile') ('3', 'Oscar Wilde', 'Be yourself everyone else is already taken')
As you can see, we have passed csv.QUOTE_ALL
to the quoting
parameter. It is a constant defined by the csv
module.
csv.QUOTE_ALL
specifies the reader object that all the values in the CSV file are present inside quotation marks.
There are 3 other predefined constants you can pass to the quoting
parameter:
csv.QUOTE_MINIMAL
- Specifiesreader
object that CSV file has quotes around those entries which contain special characters such as delimiter, quotechar or any of the characters in lineterminator.csv.QUOTE_NONNUMERIC
- Specifies thereader
object that the CSV file has quotes around the non-numeric entries.csv.QUOTE_NONE
- Specifies the reader object that none of the entries have quotes around them.
Dialects in CSV module
Notice in Example 4 that we have passed multiple parameters (quoting
and skipinitialspace
) to the csv.reader()
function.
This practice is acceptable when dealing with one or two files. But it will make the code more redundant and ugly once we start working with multiple CSV files with similar formats.
As a solution to this, the csv
module offers dialect
as an optional parameter.
Dialect helps in grouping together many specific formatting patterns like delimiter
, skipinitialspace
, quoting
, escapechar
into a single dialect name.
It can then be passed as a parameter to multiple writer
or reader
instances.
Example 5: Read CSV files using dialect
Suppose we have a CSV file (office.csv) with the following content:
"ID"| "Name"| "Email" "A878"| "Alfonso K. Hamby"| "[email protected]" "F854"| "Susanne Briard"| "[email protected]" "E833"| "Katja Mauer"| "[email protected]"
The CSV file has initial spaces, quotes around each entry, and uses a |
delimiter.
Instead of passing three individual formatting patterns, let's look at how to use dialects to read this file.
import csv csv.register_dialect('myDialect', delimiter='|', skipinitialspace=True, quoting=csv.QUOTE_ALL) with open('office.csv', 'r') as csvfile: reader = csv.reader(csvfile, dialect='myDialect') for row in reader: print(row)
Output
('ID', 'Name', 'Email') ("A878", 'Alfonso K. Hamby', '[email protected]') ("F854", 'Susanne Briard', '[email protected]') ("E833", 'Katja Mauer', '[email protected]')
From this example, we can see that the csv.register_dialect()
function is used to define a custom dialect. It has the following syntax:
csv.register_dialect(name(, dialect(, **fmtparams)))
The custom dialect requires a name in the form of a string. Other specifications can be done either by passing a sub-class of Dialect
class, or by individual formatting patterns as shown in the example.
While creating the reader object, we pass dialect='myDialect'
to specify that the reader instance must use that particular dialect.
The advantage of using dialect
is that it makes the program more modular. Notice that we can reuse 'myDialect' to open other files without having to re-specify the CSV format.
Read CSV files with csv.DictReader()
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 a CSV file (people.csv) with the following entries:
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
Using csv.Sniffer class
The Sniffer
class is used to deduce the format of a CSV file.
The Sniffer
class offers two methods:
sniff(sample, delimiters=None)
- This function analyses a given sample of the CSV text and returns aDialect
subclass that contains all the parameters deduced.
An optional delimiters parameter can be passed as a string containing possible valid delimiter characters.
has_header(sample)
- This function returnsTrue
orFalse
based on analyzing whether the sample CSV has the first row as column headers.
Let's look at an example of using these functions:
Example 7: Using csv.Sniffer() to deduce the dialect of CSV files
Suppose we have a CSV file (office.csv) with the following content:
"ID"| "Name"| "Email" A878| "Alfonso K. Hamby"| "[email protected]" F854| "Susanne Briard"| "[email protected]" E833| "Katja Mauer"| "[email protected]"
Let's look at how we can deduce the format of this file using csv.Sniffer()
class:
import csv with open('office.csv', 'r') as csvfile: sample = csvfile.read(64) has_header = csv.Sniffer().has_header(sample) print(has_header) deduced_dialect = csv.Sniffer().sniff(sample) with open('office.csv', 'r') as csvfile: reader = csv.reader(csvfile, deduced_dialect) for row in reader: print(row)
Output
True ('ID', 'Name', 'Email') ('A878', 'Alfonso K. Hamby', '[email protected]') ('F854', 'Susanne Briard', '[email protected]') ('E833', 'Katja Mauer', '[email protected]')
As you can see, we read only 64 characters of office.csv and stored it in the sample variable.
This sample was then passed as a parameter to the Sniffer().has_header()
function. It deduced that the first row must have column headers. Thus, it returned True
which was then printed out.
Demikian pula, sampel juga diteruskan ke Sniffer().sniff()
fungsi tersebut. Ini mengembalikan semua parameter yang disimpulkan sebagai Dialect
subclass yang kemudian disimpan dalam variabel deduced_dialect.
Kemudian, kami membuka kembali file CSV dan meneruskan deduced_dialect
variabel sebagai parameter ke csv.reader()
.
Ia mampu memprediksi dengan benar delimiter
, quoting
dan skipinitialspace
parameter di file office.csv tanpa kami secara eksplisit menyebutkannya.
Catatan: Modul csv juga dapat digunakan untuk ekstensi file lain (seperti: .txt ) selama isinya dalam struktur yang benar.
Bacaan yang Disarankan: Menulis ke File CSV dengan Python