Read First Line of Csv File Python
Summary: in this tutorial, you'll learn how to read a CSV file in Python using the built-in csv module.
What is a CSV file
CSV stands for comma-separated values. A CSV file is a delimited text file that uses a comma to separate values.
A CSV file consists of ane or more lines. Each line is a data tape. And each data record consists of one or more values separated by commas. In add-on, all the lines of a CSV file have the same number of values.
Typically, you utilise a CSV file to store tabular information in plain text. The CSV file format is quite popular and supported past many software applications such as Microsoft Excel and Google Spreadsheet.
Reading a csv file in Python
To read a CSV file in Python, yous follow these steps:
Beginning, import the csv module:
import csv
Code language: Python ( python ) 2nd, open the CSV file using the built-in open() function in the read mode:
f = open('path/to/csv_file')
Code linguistic communication: Python ( python ) If the CSV contains UTF8 characters, you demand to specify the encoding like this:
f = open('path/to/csv_file', encoding='UTF8')
Code language: Python ( python ) Third, laissez passer the file object (f) to the reader() part of the csv module. The reader() function returns a csv reader object:
Code linguistic communication: Python ( python )
csv_reader = csv.reader(f)
The csv_reader is an iterable object of lines from the CSV file. Therefore, y'all tin iterate over the lines of the CSV file using a for loop:
for line in csv_reader: print(line)
Code language: Python ( python ) Each line is a listing of values. To access each value, you lot use the square bracket notation []. The offset value has an index of 0. The second value has an index of 1, and and then on.
For example, the following accesses the starting time value of a particular line:
line[0]
Code language: Python ( python ) Finally, always close the file once you're no longer admission it by calling the close() method of the file object:
Lawmaking linguistic communication: Python ( python )
f.close()
It'll be easier to utilise the with statement and then that you don't need to explicitly call the close() method.
The following illustrates all the steps for reading a CSV file:
import csv with open('path/to/csv_file', 'r') as f: csv_reader = csv.reader(f) for line in csv_reader: # process each line impress(line)
Code linguistic communication: Python ( python ) Reading a CSV file examples
Nosotros'll use the state.csv file that contains country information including proper name, surface area, ii-letter country code, 3-letter land code:
Download country.csv file
The post-obit shows how to read the country.csv file and display each line to the screen:
import csv with open('land.csv', encoding="utf8") as f: csv_reader = csv.reader(f) for line in csv_reader: print(line)
Lawmaking language: Python ( python ) Output:
['name', 'expanse', 'country_code2', 'country_code3'] ['Afghanistan', '652090.00', 'AF', 'AFG'] ['Albania', '28748.00', 'AL', 'ALB'] ['Algeria', '2381741.00', 'DZ', 'DZA'] ['American Samoa', '199.00', 'As', 'ASM'] ...
Lawmaking language: Python ( python ) The state.csv has the outset line as the header. To divide the header and information, y'all use the enumerate() office to become the index of each line:
import csv with open up('country.csv', encoding="utf8") every bit f: csv_reader = csv.reader(f) for line_no, line in enumerate(csv_reader, 1): if line_no == 1: print('Header:') impress(line) # header print('Data:') else: print(line) # information
Code linguistic communication: Python ( python ) In this instance, nosotros use the enumerate() function and specify the alphabetize of the first line as 1.
Inside the loop, if the line_no is is 1, the line is the header. Otherwise, it'southward a information line.
Some other way to skip the header is to employ the side by side() function. The next() function forwards to the reader to the next line. For case:
import csv with open('state.csv', encoding="utf8") as f: csv_reader = csv.reader(f) # skip the first row side by side(csv_reader) # evidence the data for line in csv_reader: impress(line)
Code language: Python ( python ) The following reads the country.csv file and calculate the total areas of all countries:
import csv total_area = 0 # calculate the total area of all countries with open('country.csv', encoding="utf8") equally f: csv_reader = csv.reader(f) # skip the header next(csv_reader) # calculate full for line in csv_reader: total_area += float(line[1]) print(total_area)
Code language: Python ( python ) Output:
148956306.9
Lawmaking language: Python ( python ) Reading a CSV file using the DictReader class
When you use the csv.reader() office, you can access values of the CSV file using the bracket notation such as line[0], line[1], and so on. However, using the csv.reader() function has two main limitations:
- Showtime, the way to admission the values from the CSV file is not and then obvious. For example, the
line[0]implicitly means the state name. It would be more expressive if you can access the country name similarline['country_name']. - Second, when the social club of columns from the CSV file is inverse or new columns are added, you demand to modify the code to become the right information.
This is where the DictReader class comes into play. The DictReader class also comes from the csv module.
The DictReader class allows you to create an object similar a regular CSV reader. Merely it maps the data of each line to a dictionary (dict) whose keys are specified by the values of the first line.
By using the DictReader class, y'all can admission values in the country.csv file like line['name'], line['surface area'], line['country_code2'], and line['country_code3'].
The following example uses the DictReader class to read the state.csv file:
import csv with open('state.csv', encoding="utf8") as f: csv_reader = csv.DictReader(f) # skip the header adjacent(csv_reader) # show the information for line in csv_reader: print(f"The area of {line['proper name']} is {line['area']} km2")
Code language: Python ( python ) Output:
The area of Afghanistan is 652090.00 km2 The area of Albania is 28748.00 km2 The area of Algeria is 2381741.00 km2 ...
Lawmaking language: Python ( python ) If you lot desire to have unlike field names other than the ones specified in the first line, you can explicitly specify them by passing a listing of field names to the DictReader() constructor like this:
import csv fieldnames = ['country_name', 'area', 'code2', 'code3'] with open('country.csv', encoding="utf8") as f: csv_reader = csv.DictReader(f, fieldnames) next(csv_reader) for line in csv_reader: impress(f"The surface area of {line['country_name']} is {line['expanse']} km2")
Lawmaking language: Python ( python ) In this example, instead of using values from the first line as the field names, nosotros explicitly pass a listing of field names to the DictReader constructor.
Summary
- Use
csv.reader()function orcsv.DictReaderclass to read data from a CSV file.
Did you observe this tutorial helpful ?
Source: https://www.pythontutorial.net/python-basics/python-read-csv-file/
0 Response to "Read First Line of Csv File Python"
Postar um comentário