user5864802
user5864802

Reputation: 19

Reading Numbers in a Text file line by line and running them through a small comparison script using python csv

I am new to python and I am trying to import a txt file, read it line by line ( each line only contains numbers) and the file looks like:

350
490
700
10
59
2000

So far I have :

import sys
import csv

with open("file.txt") as f:

        c = csv.reader(f, delimiter=' ', skipinitialspace=True)
        line = []
        for line in c:
                print(line)
        if line > 300 and line < 500:
                print "a"
        elif line > 501 and line < 701:
                print "b"
        else:
                print "c"

Although this reads every line but it fails to execute the if statement and only prints "c" . I am wondering how I can fix this issue. I really appreciate the help.

Upvotes: 0

Views: 53

Answers (3)

FMc
FMc

Reputation: 42421

When you read data from a file, the values are strings. If you want to treat them as numbers, you need to convert the data first. For example:

n = int(line)

if n > 300 and n < 500:
    # etc...

In addition, the structure of your program is a bit unusual, because the conditional logic is completely outside the line-by-line processing. A more typical approach would be to iterate over the data yielded by the CSV reader, performing conditional logic on each line. Also note that the reader returns a list of values (or fields, as they are often called when dealing with CSV files). Here's an illustration:

reader = csv.reader(f, delimiter=' ', skipinitialspace=True)
for fields in reader:
    val = int(fields[0])
    if val > 300 and val < 500:
        print 'a'
    elif val > 501 and val < 701:
        print 'b'
    else:
        print 'c'

Upvotes: 2

Martin Evans
Martin Evans

Reputation: 46779

Your code has an indenting issue, also as has been mentioned, the csv module treats all entries in your file as strings, as such you first need to convert each entry into an integer using the int command as follows:

import sys
import csv

with open("file.txt") as f:
    c = csv.reader(f, delimiter=' ', skipinitialspace=True)

    for line in c:
        print line
        value = int(line[0])  # convert the first column to an integer (in case there are more than 1)

        if 300 < value < 500:
            print "a"
        elif 501 < value < 701:
            print "b"
        else:
            print "c"

For your example, this would then display the following output:

['350']
a
['490']
a
['700']
b
['10']
c
['59']
c
['2000']
c

Note, your code would print c for a value of 500. If you wanted to include it with a you would need to use <= 500.

Upvotes: 0

furas
furas

Reputation: 142869

you have to convert text from file into integers.

Upvotes: 1

Related Questions