我简单地解释了有关从 csv 文件读取数据的 python 程序。您只需要执行一些步骤即可完成从 csv 文件 python 读取数据。
在这种情况下,我们将使用一个演示。demo.csv文件中的 ID、姓名和电子邮件字段。然后,要从 csv 文件中读取数据,我们将使用open()和reader()函数。
话不多说,我们来看下面的代码示例:
那么让我们看看下面的例子:
示例 1:Python 读取 CSV 文件
main.py
from csv import reader # open demo.csv file in read mode with open('demo.csv', 'r') as readObj: # pass the file object to reader() to get the reader object csvReader = reader(readObj) # Iterate over each row in the csv using reader object for row in csvReader: # row variable is a list that represents a row in csv print(row)
输出
['ID', 'Name', 'Email'] ['1', 'Bhavesh Sonagra', 'bhavesh@gmail.com'] ['2', 'Nikhil Patel', 'nikhil@gmail.com'] ['3', 'Piyush Kamani', 'piyush@gmail.com']
示例 2:Python 读取不带标题的 CSV 文件
main.py
from csv import reader # skip first line from demo.csv with open('demo.csv', 'r') as readObj: csvReader = reader(readObj) header = next(csvReader) # Check file as empty if header != None: # Iterate over each row after the header in the csv for row in csvReader: # row variable is a list that represents a row in csv print(row)
输出
['ID', 'Name', 'Email'] ['1', 'Bhavesh Sonagra', 'bhavesh@gmail.com'] ['2', 'Nikhil Patel', 'nikhil@gmail.com'] ['3', 'Piyush Kamani', 'piyush@gmail.com']
示例 3:Python 逐行读取 CSV 文件
main.py
from csv import DictReader # open demo.csv file in read mode with open('demo.csv', 'r') as readObj: # Pass the file object to DictReader() to get the DictReader object csvDictReader = DictReader(readObj) # get over each line as a ordered dictionary for row in csvDictReader: # row variable is a dictionary that represents a row in csv print(row)
输出
{'ID': '1', 'Name': 'Bhavesh Sonagra', 'Email': 'bhavesh@gmail.com'} {'ID': '2', 'Name': 'Nikhil Patel', 'Email': 'nikhil@gmail.com'} {'ID': '3', 'Name': 'Piyush Kamani', 'Email': 'piyush@gmail.com'}
它会帮助你……