1
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 = 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.

I need this construction exact as it is for another function and later operations which are not listed here.

The append operations works fine so far. The issue here is to iterate over the file like I described.

dan_from_d
  • 13
  • 5
  • Does this answer your question? [Reading rows from a CSV file in Python](https://stackoverflow.com/questions/13428318/reading-rows-from-a-csv-file-in-python) – Christopher Peisert Oct 25 '20 at 13:43

2 Answers2

1

This solution is reading the csv file line by line and returns a list of lists represents the raw csv file.

  • bonus - you can ignore the csv headers if you need to :)
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!

Alon Barad
  • 1,491
  • 1
  • 13
  • 26
0

hope this will read the csv file line by line

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))
Umair Mubeen
  • 823
  • 4
  • 22