Reading Csv Files With Commas in Fields Java
This article explains how to load and parse a CSV file in Python.
First of all, what is a CSV ?
CSV (Comma Separated Values) is a elementary file format used to store tabular information, such as a spreadsheet or database. A CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a information record. Each record consists of one or more fields, separated past commas. The use of the comma as a field separator is the source of the proper noun for this file format.
For working CSV files in python, there is an inbuilt module called csv.
Reading a CSV file
Python
import
csv
filename
=
"aapl.csv"
fields
=
[]
rows
=
[]
with
open
(filename,
'r'
) as csvfile:
csvreader
=
csv.reader(csvfile)
fields
=
next
(csvreader)
for
row
in
csvreader:
rows.append(row)
impress
("Full no. of rows:
%
d"
%
(csvreader.line_num))
impress
(
'Field names are:'
+
', '
.join(field
for
field
in
fields))
print
(
'\nFirst v rows are:\n'
)
for
row
in
rows[:
5
]:
for
col
in
row:
print
(
"%10s"
%
col,finish
=
" "
),
print
(
'\n'
)
The output of the above program looks like this:
The above example uses a CSV file aapl.csv which can be downloaded from here.
Run this program with the aapl.csv file in the same directory.
Let us try to understand this piece of lawmaking.
with open(filename, 'r') as csvfile: csvreader = csv.reader(csvfile)
- Here, we starting time open the CSV file in READ mode. The file object is named equally csvfile. The file object is converted to csv.reader object. We save the csv.reader object every bit csvreader.
fields = csvreader.next()
- csvreader is an iterable object. Hence, .next() method returns the current row and advances the iterator to the next row. Since the first row of our csv file contains the headers (or field names), we save them in a listing chosen fields.
for row in csvreader: rows.append(row)
- Now, nosotros iterate through the remaining rows using a for loop. Each row is appended to a list chosen rows. If you effort to impress each row, i can find that a row is nothing but a list containing all the field values.
print("Total no. of rows: %d"%(csvreader.line_num))
- csvreader.line_num is nothing but a counter which returns the number of rows that have been iterated.
Writing to a CSV file
Python
import
csv
fields
=
[
'Name'
,
'Co-operative'
,
'Year'
,
'CGPA'
]
rows
=
[ [
'Nikhil'
,
'COE'
,
'ii'
,
'9.0'
],
[
'Sanchit'
,
'COE'
,
'2'
,
'9.one'
],
[
'Aditya'
,
'Information technology'
,
'2'
,
'9.3'
],
[
'Sagar'
,
'SE'
,
'1'
,
'ix.5'
],
[
'Prateek'
,
'MCE'
,
'iii'
,
'7.8'
],
[
'Sahil'
,
'EP'
,
'ii'
,
'9.1'
]]
filename
=
"university_records.csv"
with
open
(filename,
'west'
) as csvfile:
csvwriter
=
csv.author(csvfile)
csvwriter.writerow(fields)
csvwriter.writerows(rows)
Let us attempt to understand the above lawmaking in pieces.
- fields and rows have been already defined. fields is a listing containing all the field names. rows is a list of lists. Each row is a listing containing the field values of that row.
with open(filename, 'w') as csvfile: csvwriter = csv.author(csvfile)
- Here, we start open the CSV file in WRITE way. The file object is named every bit csvfile. The file object is converted to csv.writer object. Nosotros relieve the csv.writer object as csvwriter.
csvwriter.writerow(fields)
- Now we use writerow method to write the first row which is nothing but the field names.
csvwriter.writerows(rows)
- We apply writerows method to write multiple rows at once.
Writing a lexicon to a CSV file
Python
import
csv
mydict
=
[{
'branch'
:
'COE'
,
'cgpa'
:
'9.0'
,
'proper noun'
:
'Nikhil'
,
'year'
:
'two'
},
{
'branch'
:
'COE'
,
'cgpa'
:
'9.1'
,
'proper name'
:
'Sanchit'
,
'yr'
:
'ii'
},
{
'branch'
:
'Information technology'
,
'cgpa'
:
'nine.3'
,
'name'
:
'Aditya'
,
'twelvemonth'
:
'2'
},
{
'branch'
:
'SE'
,
'cgpa'
:
'9.5'
,
'name'
:
'Sagar'
,
'year'
:
'1'
},
{
'co-operative'
:
'MCE'
,
'cgpa'
:
'7.eight'
,
'proper noun'
:
'Prateek'
,
'year'
:
'three'
},
{
'branch'
:
'EP'
,
'cgpa'
:
'nine.1'
,
'proper name'
:
'Sahil'
,
'year'
:
'2'
}]
fields
=
[
'name'
,
'branch'
,
'year'
,
'cgpa'
]
filename
=
"university_records.csv"
with
open
(filename,
'w'
) as csvfile:
writer
=
csv.DictWriter(csvfile, fieldnames
=
fields)
writer.writeheader()
author.writerows(mydict)
In this instance, we write a dictionary mydict to a CSV file.
with open(filename, 'due west') as csvfile: writer = csv.DictWriter(csvfile, fieldnames = fields)
- Here, the file object (csvfile) is converted to a DictWriter object.
Here, we specify the fieldnames as an argument.
author.writeheader()
- writeheader method only writes the first row of your csv file using the pre-specified fieldnames.
author.writerows(mydict)
- writerows method merely writes all the rows just in each row, information technology writes only the values(not keys).
And so, in the stop, our CSV file looks similar this:
Important Points:
- In csv modules, an optional dialect parameter can be given which is used to ascertain a set of parameters specific to a detail CSV format. By default, csv module uses excel dialect which makes them compatible with excel spreadsheets. You lot can define your own dialect using register_dialect method.
Here is an example:
Now, while defining a csv.reader or csv.writer object, we can specify the dialect like
this:
- At present, consider that a CSV file looks like this in manifestly-text:
- We notice that the delimiter is not a comma just a semi-colon. As well, the rows are separated by two newlines instead of one. In such cases, we tin specify the delimiter and line terminator equally follows:
Then, this was a brief, yet concise discussion on how to load and parse CSV files in a python program.
This blog is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks principal page and aid other Geeks.
Please write comments if yous find anything incorrect, or you desire to share more information about the topic discussed above.
Source: https://www.geeksforgeeks.org/working-csv-files-python/
0 Response to "Reading Csv Files With Commas in Fields Java"
Post a Comment