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.

1

2 Answers 2

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!

Sign up to request clarification or add additional context in comments.

Comments

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.