PythonDabble - 1 month ago 4x
Python Question

# How to read the elements as "columns" from a file?

I have the following file that has a number of rows as follows

``````qt1l    1   A   B   90  1   3.00
jqlt1l  2   B   Z   20  5   6.00
ahyttl  3   F   O   45  33  53.00
kqll    4   L   L   70  22  22.00
gqlt1l  5   T   U   90  6   77.00

with open('c:/test/file.txt','r') as f:
``````

In this program I take x,y and z input. I read the data row wise. For example, take row[0] for example. Here, I need to compare if "column 4" =! "z", "column 3" -->"A" to "column 4" ---> "B" (col3 =! col4). Check if "column 5" >= x, "column 6" >= y and "column 7" >= 8. If all are yes then I have a count that increments by 1. The following is the code:

`````` x = input("Enter value for x: ") # Take x = 1
y = input("Enter value for y: ") # Take x = 1
z = input("Enter value for z: ") # Take x = 1

for line in infile:
if[col4] =I "Z":
continue
if [col3] != [col4]:
continue
if [col5] >= x:
continue
if [col6] >= y:
continue
if [col7] >= z:
continue
count += 1
print [col2]
finalcount.append(count)
print "The final count is" + str(finalcount)
``````

The problem is that these "columns" can only be accessed as a certain element number --> inputfile[0][8]. So if I need to check if "column 4" > 80..then I run into trouble because I need to check if inputfile[0][something] >= 8 and inputfile[0][something+1] >= 0.

Can you think of a easy way to bypass the problem? I also need help to check if my code is running fine in the end with desired output.
Here the output should be

``````1
3
5
The final count is 3
``````

``````x = 1 # example values
y = 1
z = 1

count = 0

for line in inputfile:
# This splits on whitespace.
# E.g., for the first row:
# columns = ['qt1l', '1', 'A', 'B', '90', '1', '3.00']
columns = line.split()

# Note that indexes into lists are 0-based, so "column 4" is columns[3]
if (columns[3] != "Z" and
columns[2] != columns[3] and
float(columns[4]) >= x and # Convert from str to float!
float(columns[5]) >= y and
float(columns[6]) >= z):

# If all the conditions are met, increment your counter
count += 1
print(columns[1])

print("The final count is {}".format(count))
``````

There were a number of issues with your code:

1. `=+` and `=!` instead of `+=` and `!=`.
2. `continue` means "Go immediately to the next iteration of the loop." With your `continue` statements, as soon as one condition passed, you were going to skip over that row entirely.
3. There are some missing bits of your code... you show reading the file into `inputfile` but later use `qual`. You don't define `count` or `finalcount` (which I guess is some sort of list?). In the future, make sure to share complete runnable code.