У овом упутству ћемо научити да читамо ЦСВ датотеке у различитим форматима у Питхону уз помоћ примера.
csv
За овај задатак ћемо користити искључиво модул уграђен у Питхон. Али прво, мораћемо да увозимо модул као:
import csv
Већ смо покрили основе како се користи csv
модул за читање и писање у ЦСВ датотеке. Ако немате појма о коришћењу csv
модула, погледајте наш водич о Питхон ЦСВ: Читање и писање ЦСВ датотека
Основна употреба цсв.реадер ()
Погледајмо основни пример коришћења csv.reader()
за освежавање постојећег знања.
Пример 1: Читајте ЦСВ датотеке помоћу цсв.реадер ()
Претпоставимо да имамо ЦСВ датотеку са следећим уносима:
СН, име, допринос 1, Линус Торвалдс, Линук кернел 2, Тим Бернерс-Лее, Ворлд Виде Веб 3, Гуидо ван Россум, Питхон програмирање
Садржај датотеке можемо читати помоћу следећег програма:
import csv with open('innovators.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row)
Оутпут
('СН', 'Наме', 'Цонтрибутион') ('1', 'Линус Торвалдс', 'Линук Кернел') ('2', 'Тим Бернерс-Лее', 'Ворлд Виде Веб') ('3' , 'Гуидо ван Россум', 'Питхон програмирање')
Овде смо отворили датотеку инноваторс.цсв у режиму читања помоћу open()
функције.
Да бисте сазнали више о отварању датотека у Питхону, посетите: Улаз / излаз Питхон датотеке
Затим csv.reader()
се користи за читање датотеке која враћа итерабилни reader
објекат.
Затим се reader
објекат итерира помоћу for
петље за испис садржаја сваког реда.
Сада ћемо погледати ЦСВ датотеке у различитим форматима. Затим ћемо научити како прилагодити csv.reader()
функцију да их чита.
ЦСВ датотеке са прилагођеним граничницима
Подразумевано се зарез користи као граничник у ЦСВ датотеци. Међутим, неке ЦСВ датотеке могу користити граничнике који нису зарез. Мало је популарних |
и
.
Претпоставимо да је датотека инноваторс.цсв у примеру 1 користила таб као граничник. Да бисмо прочитали датотеку, функцији можемо проследити додатни delimiter
параметар csv.reader()
.
Узмимо пример.
Пример 2: Прочитајте ЦСВ датотеку која има раздвајач картице
import csv with open('innovators.csv', 'r') as file: reader = csv.reader(file, delimiter = ' ') for row in reader: print(row)
Оутпут
('СН', 'Наме', 'Цонтрибутион') ('1', 'Линус Торвалдс', 'Линук Кернел') ('2', 'Тим Бернерс-Лее', 'Ворлд Виде Веб') ('3' , 'Гуидо ван Россум', 'Питхон програмирање')
Као што видимо, опционални параметар delimiter = ' '
помаже у одређивању reader
објекта који ЦСВ датотека из које читамо има табулаторе као граничник.
ЦСВ датотеке са почетним размацима
Неке ЦСВ датотеке након разграничења могу имати размак. Када користимо подразумевану csv.reader()
функцију за читање ових ЦСВ датотека, добићемо и размаке у излазу.
Да бисмо уклонили ове почетне размаке, морамо проследити додатни параметар тзв skipinitialspace
. Погледајмо пример:
Пример 3: Читајте ЦСВ датотеке са почетним размацима
Претпоставимо да имамо ЦСВ датотеку која се зове пеопле.цсв са следећим садржајем:
СН, Име, Град 1, Џон, Вашингтон 2, Ерик, Лос Анђелес 3, Бред, Тексас
ЦСВ датотеку можемо прочитати на следећи начин:
import csv with open('people.csv', 'r') as csvfile: reader = csv.reader(csvfile, skipinitialspace=True) for row in reader: print(row)
Оутпут
('СН', 'Име', 'Град') ('1', 'Јохн', 'Васхингтон') ('2', 'Ериц', 'Лос Ангелес') ('3', 'Брад', ' Текас ')
Програм је сличан осталим примерима, али има додатни skipinitialspace
параметар који је постављен на Тачно.
То омогућава reader
објекту да зна да уноси имају почетни размак. Као резултат, уклањају се почетни размаци који су били присутни након граничника.
ЦСВ датотеке са наводницима
Неке ЦСВ датотеке могу имати цитате око сваког или неких уноса.
Узмимо за пример куотес.цсв са следећим уносима:
„СН“, „Име“, „Цитати“ 1, Буда, „Оно што мислимо да смо постали“ 2, Марк Твен, „Никад се не кајте због било чега што вас је насмејало“ 3, Осцар Вилде, „Буди свој, сви остали су већ узети
Коришћење csv.reader()
у минималном режиму резултираће исписом под наводницима.
Да бисмо их уклонили, мораћемо да користимо други опционални параметар који се зове quoting
.
Погледајмо пример како се чита горе наведени програм.
Пример 4: Читајте ЦСВ датотеке са наводницима
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)
Оутпут
('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.
Слично томе, узорак је такође прослеђен Sniffer().sniff()
функцији. Вратио је све изведене параметре као Dialect
поткласу која је затим била ускладиштена у променљивој дедуцед_диалецт.
Касније смо поново отворили ЦСВ датотеку и проследили deduced_dialect
променљиву као параметар csv.reader()
.
То правилно био у стању да предвиди delimiter
, quoting
а skipinitialspace
параметри у оффице.цсв фајл без нас их експлицитно спомиње.
Напомена: цсв модул се такође може користити за друге наставке датотека (попут: .ткт ) све док је њихов садржај у одговарајућој структури.
Препоручено читање: Запишите у ЦСВ датотеке на Питхону