📜  如何在Python读取CSV文件

📅  最后修改于: 2020-10-28 01:43:02             🧑  作者: Mango

如何在Python读取CSV文件?

CSV文件代表用逗号分隔的值文件。它是一种纯文本文件,其中信息以表格形式组织。它只能包含实际的文本数据。文本数据不需要用逗号(,)分隔。还有许多分隔字符,例如制表符(\ t),冒号(:)和分号(;),可用作分隔符。让我们了解以下示例。

在这里,我们有一个example.txt文件。

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(),它带有两个参数文件对象和定界符。我们使用0初始化了count_line变量。它计算csv文件中的行数。

现在,我们迭代了csv文件对象的每一行。通过删除定界符返回数据。返回的第一行包含列名。