简体   繁体   English

Python 循环逐行读取CSV文件

[英]Python read CSV file line by line in loop

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

How is it possible to read the file line by line while looping?循环时如何逐行读取文件? One line for every c .每个c

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

and so on and so on...等等等等...

islice , pandas , and so on, didn't work it out for me so far. islicepandas等等,到目前为止还没有为我解决。

I need this construction exact as it is for another function and later operations which are not listed here.我需要这个结构,因为它是另一个 function 以及此处未列出的后续操作。

The append operations works fine so far.到目前为止, append操作运行良好。 The issue here is to iterate over the file like I described.这里的问题是像我描述的那样迭代文件。

This solution is reading the csv file line by line and returns a list of lists represents the raw csv file.此解决方案逐行读取 csv 文件并返回表示原始 csv 文件的列表列表。

  • bonus - you can ignore the csv headers if you need to:)奖金 - 如果需要,您可以忽略 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)

Hoped it helps!希望它有所帮助!

hope this will read the csv file line by line希望这会逐行读取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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM