Home >Backend Development >Python Tutorial >How to read a column in a csv file in python
You can read specific columns from a CSV file through Python's csv module. The steps are as follows: Import the csv module. Open the CSV file. Create a CSV reader object. Optional: Skip the header row. Loop through the rows, accessing the columns. Close the file.
How to read a specific column from a CSV file
To read a specific column from a CSV file, you can Use Python's csv module. The following steps explain how to do it:
Step 1: Import the csv module
<code class="python">import csv</code>
Step 2: Open the CSV file
<code class="python">with open('data.csv', 'r') as csvfile:</code>
Step 3: Create CSV Reader Object
<code class="python">reader = csv.reader(csvfile)</code>
Step 4: Skip header row (optional)
If the CSV file contains a header row , can be skipped using the following method:
<code class="python">next(reader)</code>
Step 5: Loop through the lines
<code class="python">for row in reader: # 访问列 列名 = row[列索引]</code>
Step 6: Close the file
<code class="python">csvfile.close()</code>
Example:
To read all the values in column 3 (index 2), you can use the following code:
<code class="python">import csv with open('data.csv', 'r') as csvfile: reader = csv.reader(csvfile) next(reader) # 跳过标题行 for row in reader: 列名 = row[2] print(列名)</code>
The above is the detailed content of How to read a column in a csv file in python. For more information, please follow other related articles on the PHP Chinese website!