Can you please help me with the following code:
#! /usr/bin/env python
stop = "0"
while(stop == "0"):
infile = open(raw_input("Enter input filename: "), 'r')
outfile = open(raw_input("Enter output filename: "), 'w')
err = raw_input("Give max intensity: ")
outfile.write("#" + "\n")
for line in infile.readlines()[1:]:
line = line.strip()
line_col = line.split()
if line_col[3] <= err:
outfile.write(line + "\n")
else:
del line
stop = raw_input("Would like to quit the program? Yes = 1 No = 0: ")
infile.close()
outfile.close()
The idea here is to read a file that has 5 columns of data. After prompting the user for a number (err) it is used to delete a line of data if the number in the 4th column of the file is above 'err'.
The problem is that for some reason not all the appropriate lines are deleted. If err = 500 then all 3 digit numbers above 500 (e.g 653.61511, 989.76770, 614.62500 etc...) will be deleted however those numbers that have 4 digits (e.g 1001.15637, 1628.09155, 2444.60400 etc...) are not!
The file that i am working with is given below:
-8.0 4.0 3.695 265.81021 265.8102
-8.0 4.0 3.721 274.50510 274.5051
-8.0 4.0 3.746 285.87451 285.8745
-8.0 4.0 3.771 301.65869 301.6587
-8.0 4.0 3.796 324.28391 324.2839
-8.0 4.0 3.821 356.89609 356.8961
-8.0 4.0 3.846 405.96741 405.9674
-8.0 4.0 3.872 488.77600 488.7760
-8.0 4.0 3.897 653.61511 653.6151
-8.0 4.0 3.922 1001.15637 1001.1564
-8.0 4.0 3.947 1628.09155 1628.0916
-8.0 4.0 3.972 2444.60400 2444.6040
-8.0 4.0 4.023 3092.76880 3092.7688
-8.0 4.0 4.048 2488.82031 2488.8203
-8.0 4.0 4.073 1653.13733 1653.1373
-8.0 4.0 4.098 989.76770 989.7677
-8.0 4.0 4.123 614.62500 614.6250
I am by no means an expert at coding in python so any help regarding this matter would be greatly appreciated...
The problem isn't with del
-- which, by the way, doesn't do anything here -- it's with comparing two strings.
Open up a Python interpreter and write:
"1001" < "3"
You'll get back True
. That's because Python is doing a lexicographical comparison of two strings. What you want is to compare two numbers, like this:
1001 < 3
Which gives back False
, as we'd expect.
In your code, line_col[3]
is a string, as is err
, so Python does the first type of comparison. You'll need to convert both to numbers to get behavior you'd like, by writing, for instance: float(line_col[3]) < float(err)
.