【问题标题】:Python read CSV file line by line in loopPython在循环中逐行读取CSV文件
【发布时间】:2020-10-25 13:21:52
【问题描述】:
def read_file():
    with open("bla.csv", "r") as Blabla:
        reader = csv.reader(BlaBla)

        for column in reader:
            one = column[1]
            two = column[2]
            three = column[3]
            four = column[4]

            bla_line.append([one, two, three, four])

count, c = 50, 1
while c < count:
    read_file()

    c = c + 1

如何在循环时逐行读取文件?每个c 一行。

c = 0 = read line 0
c = 1 = read line 1
c = 2 = read line 2

等等等等……

islice、pandas 等等,到目前为止还没有为我解决。

我需要这个结构,因为它是用于此处未列出的另一个功能和后续操作。

到目前为止,append 操作运行良好。这里的问题是像我描述的那样遍历文件。

【问题讨论】:

标签: python csv


【解决方案1】:

希望这将逐行读取csv 文件

with open("bla.csv") as f:
    lis = [line.split() for line in f]        # create a list of lists
    for i, x in enumerate(lis):              #print the list items 
        print "line{0} = {1}".format(i, x))

【讨论】:

    【解决方案2】:

    此解决方案是逐行读取 csv 文件并返回代表原始 csv 文件的列表列表。

    • 奖励 - 如果需要,您可以忽略 csv 标头 :)
    def read_csv(path: str, ignore_headers: bool = False):
        with open(path, 'r') as csv:
            res = []
            for line_number, line in enumerate(csv.readlines()):
                if ignore_headers and line_number == 0:
                    continue
                else:
                    res.append(line.strip().split(','))
    
        return res
    
    
    if __name__ == '__main__':
        csv_content = '''first_name,last_name,age
        John,Harris,23
        Omar,Ahmed,19'''
        with open('temp.csv', 'w') as _file:
            for line in csv_content:
                _file.write(line)
        csv = read_csv('temp.csv')
        print(csv)
        csv = read_csv('temp.csv', ignore_headers=True)
        print(csv)
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 2012-11-12
      • 1970-01-01
      相关资源
      最近更新 更多