Can I remove negative values from a list while keeping the list values as strings?
I'm trying to format a tab delimited text file where there are negative values in the data set. I'm trying to ignore lines of data where there is any negative values showing up. I want to write to an output file only rows of data that have positive values. Is there anyway to do this with a wild character that looks for "-" in the strings? I would rather not convert the list to floats if I can get away with it.
Here's the code (without any mention of negative values yet):
import sys, os
inputFileName = sys.argv[1]
outputFileName = os.path.splitext(inputFileName)[0]+"_edited.txt"
try:
infile = open(inputFileName,'r')
outfile = open(outputFileName, 'w')
line = infile.readline()
outfile.write(line)
for line in infile:
line = line.strip()
lineList = line.split('\t')
lineList = [line for line in lineList if line != '']
#print lineList
#print len(lineList)
if len(lineList) == 9:
#print lineList
line = '\t'.join(lineList)
line = line + '\n'
outfile.write(line)
infile.close()
outfile.close()
except IOError:
print inputFileName, "does not exist."
I've already (with help) gotten rid of any empty values in the above data file that has nine columns. Now I'm trying to get rid of any rows wit开发者_运维百科h negative values.
you can use a regular expression in your script to surpress anything with "-" in the beginning before outputting it. Or pipe the whole output of this script into grep -v "-" and it should surpress any lines with a negative in it.
has_negative = any(float(n) < 0 for n in re.findall(r'\-?\d+', line))
精彩评论