LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Issues with a loop in Python 2.7 (https://www.linuxquestions.org/questions/programming-9/issues-with-a-loop-in-python-2-7-a-4175622719/)

fusion1275 01-30-2018 08:18 AM

Issues with a loop in Python 2.7
 
Hi all,

So I have attempted to start learning python and have got quite far into a script which reads a csv file.

Inside the csv file I have a field that has a number. For now lets say it is 8.

In my code it reads the field, stores it in a variable so I can re-use it later on.

Now has come the time to use this variable and I want to test it in a while loop.

Here is my code extract:-

This line reads the data into the myData variable and I can then pull out the field needed. This works perfectly and gives me the number 8.
Code:

    myData = list(myReader)
    csv_host_cnt = myData[5][2]

My issue is when I try to wrap this in a loop it goes crazy on me.

Code:

    count = 0
    while count < csv_host_cnt:
        count = count + 1
        print ("hello")

So it was my thinking that the loop would go round and round 8 times until the counter catches up and I would have 8x hello's on my screen?

What it does is just run an infinite loop and I have to ctrl-C the script.

I am at a loss here as I have tried all sorts of combinations of brackets and commas and ticks. But still no joy.

I apologise if this is a very basic problem. I am still learning and by the looks of it need all the help I can get!

Thanks in advance for your time.

dugan 01-30-2018 09:02 AM

Code:

# csv_host_cnt is a string.
csv_host_cnt = myData[5][2]

Code:

# So you need:
while count < int(csv_host_cnt):


fusion1275 01-30-2018 09:06 AM

@dugan - Thank you very much. I need to get some sleep I think! How on earth did I not see that.

Thanks again

Sefyir 01-30-2018 07:06 PM

I'm not sure how you are reading the data, but doing myData = list(myReader) and then accessing it using var[1][1] will likely lead to frustration trying to access information from csv files.
Since it's a csv file, I would suggest something along these lines

Code:

import csv

file = 'myfile.csv'

with open(file) as f:
    reader = csv.reader(file)
    for row in reader:
        print(row)

This will split up each csv row into a list of columns, delimited by what you specify (default a comma)

Examples: The # represents what information the command is working with.

Code:

# data-file file.csv
a,b,c
1,2,3

Code:

data = open('file.csv')
data = list(data) # ['a,b,c\n', '1,2,3\n']
print(data[0][0]) # 'a'

Code:

with open('file.csv') as f:
    reader = csv.reader(f)
    for row in reader: # [['a', 'b', 'c'], ['1', '2', '3']]
        print(row[0]) # 'a'
                        '1'



All times are GMT -5. The time now is 08:06 PM.