首页 > 编程知识 正文

如何用 Python 读取 CSV 文件?

时间:2023-11-25 15:30:09 阅读:309142 作者:XBSB

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

这里,我们有一个示例. 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:UsersDEVANSH SHARMADesktopexample.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 模块来读取示例. csv 文件。为了读取 csv,我们在 open() 方法中传递文件的完整路径。我们使用了内置函数 csv.reader() ,它采用两个参数文件对象和分隔符。我们用 0 初始化了 count_line 变量。它计算 csv 文件的行数。

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


版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。