Python教程-如何在Python中读取CSV文件?
CSV文件代表逗号分隔值文件。它是一种以表格形式组织信息的纯文本文件。它只包含实际文本数据。文本数据不需要由逗号(,)分隔。还有许多分隔符字符,如制表符(t),冒号(:)和分号(;),可以用作分隔符。让我们理解以下示例。
在这里,我们有一个example.csv文件。
name, rollno, Department
Peter Parker, 009001, Civil
Tony Stark, 009002, Chemical
示例 -
# Read CSV file example
# Importing the csv module
import csv
# open file by passing the file path.
with open(r'C:\Users\DEVANSH SHARMA\Desktop\example.csv') as csv_file:
csv_read = csv.reader(csv_file, delimiter=',') #Delimeter is comma
count_line = 0
# Iterate the file object or each row of the file
for row in csv_read:
if count_line == 0:
print(f'Column names are {", ".join(row)}')
count_line += 1
else:
print(f'\t{row[0]} roll number is: {row[1]} and department is: {row[2]}.')
count_line += 1
print(f'Processed {count_line} lines.') # This line will print number of line fro the file
输出:
Column names are name, rollnu, Department
Peter Parker roll number is: 009001 and department is: Civil.
Tony Stark roll number is: 009002 and department is: Chemical.
Processed 3 lines.
解释:
在上面的代码中,我们导入了csv模块以读取example.csv文件。为了读取csv,我们在open()方法中传递了文件的完整路径。我们使用了内置函数csv.reader(),它接受两个参数文件对象和分隔符。我们将count_line变量初始化为0。它用于计算csv文件的行数。
现在,我们迭代了csv文件对象的每一行。数据通过删除分隔符返回。首先返回包含列名的第一行。