How to Read the First Row and Skip the Next Two in C#
This commodity explains how to load and parse a CSV file in Python.
First of all, what is a CSV ?
CSV (Comma Separated Values) is a simple file format used to shop tabular data, 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 by commas. The use of the comma as a field separator is the source of the name for this file format.
For working CSV files in python, in that location is an inbuilt module chosen csv.
Reading a CSV file
Python
import csv
filename = "aapl.csv"
fields = []
rows = []
with open (filename, 'r' ) every bit csvfile:
csvreader = csv.reader(csvfile)
fields = side by side (csvreader)
for row in csvreader:
rows.append(row)
print ("Total no. of rows: % d" % (csvreader.line_num))
print ( 'Field names are:' + ', ' .join(field for field in fields))
impress ( '\nFirst 5 rows are:\north' )
for row in rows[: 5 ]:
for col in row:
print ( "%10s" % col,stop = " " ),
print ( '\n' )
The output of the above programme looks similar this:
The to a higher place example uses a CSV file aapl.csv which can be downloaded from here.
Run this programme with the aapl.csv file in the aforementioned directory.
Let united states of america try to sympathise this piece of lawmaking.
with open(filename, 'r') every bit csvfile: csvreader = csv.reader(csvfile)
- Here, we commencement open up the CSV file in READ style. The file object is named as csvfile. The file object is converted to csv.reader object. We save the csv.reader object equally csvreader.
fields = csvreader.side by side()
- csvreader is an iterable object. Hence, .next() method returns the electric current row and advances the iterator to the next row. Since the beginning row of our csv file contains the headers (or field names), we save them in a listing called fields.
for row in csvreader: rows.append(row)
- Now, we iterate through the remaining rows using a for loop. Each row is appended to a list called rows. If you try to print each row, i can discover that a row is nothing but a list containing all the field values.
print("Full 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 = [ 'Proper name' , 'Branch' , 'Yr' , 'CGPA' ]
rows = [ [ 'Nikhil' , 'COE' , 'ii' , 'nine.0' ],
[ 'Sanchit' , 'COE' , 'ii' , 'nine.ane' ],
[ 'Aditya' , 'IT' , 'two' , '9.3' ],
[ 'Sagar' , 'SE' , '1' , 'nine.5' ],
[ 'Prateek' , 'MCE' , '3' , '7.8' ],
[ 'Sahil' , 'EP' , '2' , '9.1' ]]
filename = "university_records.csv"
with open (filename, 'w' ) as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(fields)
csvwriter.writerows(rows)
Allow us try to empathise the above code in pieces.
- fields and rows accept been already defined. fields is a list containing all the field names. rows is a list of lists. Each row is a list containing the field values of that row.
with open(filename, 'w') as csvfile: csvwriter = csv.writer(csvfile)
- Here, we kickoff open up the CSV file in WRITE mode. The file object is named as csvfile. The file object is converted to csv.writer object. We salvage the csv.writer object as csvwriter.
csvwriter.writerow(fields)
- Now we use writerow method to write the first row which is zero but the field names.
csvwriter.writerows(rows)
- We apply writerows method to write multiple rows at once.
Writing a dictionary to a CSV file
Python
import csv
mydict = [{ 'branch' : 'COE' , 'cgpa' : '9.0' , 'name' : 'Nikhil' , 'year' : 'two' },
{ 'branch' : 'COE' , 'cgpa' : '9.1' , 'name' : 'Sanchit' , 'year' : '2' },
{ 'branch' : 'It' , 'cgpa' : '9.three' , 'proper name' : 'Aditya' , 'year' : '2' },
{ 'branch' : 'SE' , 'cgpa' : 'ix.5' , 'name' : 'Sagar' , 'twelvemonth' : '1' },
{ 'branch' : 'MCE' , 'cgpa' : '7.eight' , 'name' : 'Prateek' , 'yr' : '3' },
{ 'branch' : 'EP' , 'cgpa' : 'ix.1' , 'name' : 'Sahil' , 'year' : 'ii' }]
fields = [ 'name' , 'branch' , 'year' , 'cgpa' ]
filename = "university_records.csv"
with open (filename, 'due west' ) as csvfile:
author = csv.DictWriter(csvfile, fieldnames = fields)
writer.writeheader()
writer.writerows(mydict)
In this example, 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 statement.
writer.writeheader()
- writeheader method just writes the first row of your csv file using the pre-specified fieldnames.
author.writerows(mydict)
- writerows method just writes all the rows but in each row, it writes simply the values(not keys).
Then, in the end, our CSV file looks like this:
Of import Points:
- In csv modules, an optional dialect parameter tin can be given which is used to define a set of parameters specific to a item CSV format. By default, csv module uses excel dialect which makes them uniform with excel spreadsheets. You tin can define your own dialect using register_dialect method.
Hither is an instance:
At present, while defining a csv.reader or csv.author object, we can specify the dialect like
this:
- Now, consider that a CSV file looks like this in plain-text:
- Nosotros detect that the delimiter is not a comma but a semi-colon. As well, the rows are separated by ii newlines instead of one. In such cases, we tin specify the delimiter and line terminator as follows:
And so, this was a brief, yet curtailed discussion on how to load and parse CSV files in a python programme.
This web log is contributed by Nikhil Kumar. If y'all like GeeksforGeeks and would similar to contribute, you can as well write an commodity using write.geeksforgeeks.org or post your article to review-squad@geeksforgeeks.org. See your commodity actualization on the GeeksforGeeks main page and help other Geeks.
Delight write comments if you find anything incorrect, or you want to share more than data about the topic discussed above.
Source: https://www.geeksforgeeks.org/working-csv-files-python/
Post a Comment for "How to Read the First Row and Skip the Next Two in C#"