首页 > 解决方案 > 我想在 Python 中将逗号分隔的文件作为数组读取

问题描述

我有文本文件

01,Jay,Sharma
02,Rushi,Patel

我想将此文本文件作为数组读取并希望输出为

student no : 01
Name : Jay
Surname : Sharma
student no : 02
Name : Rushi
Surname : Patel

实际上我是 Python 的新手,我可以将它作为数组读取,但我想要准确的输出,请任何人帮助我。

class RowReader:
    def fileRead(self,filepath):
        textfile = open(filepath, 'r')
        data = []
        for line in textfile:
            row_data = line.strip("\n").split(',')
            print(row_data)

file = RowReader()
file.fileRead(file_path)

先感谢您

标签: pythonarrayspython-3.xarraylist

解决方案


有一个库可以在 Python 中读取 csv 文件:csv. 您可以使用它轻松读取 csv 文件。

import csv

data = []
with open("filename.csv", "r") as f:
    reader = csv.reader(f)
    for line in reader:
        data.append(line)

for d in data:
    print("student no : {}\nName : {}\nSurname : {}".format(
        d[0], d[1], d[2]))

推荐阅读