我有两列的编号,我想比较它们。 然后输出文件在第2列中较小,在第1列中较大。
例如,下面是我的XX.csv文件。
C1,C2
1015,945
1028,958
1901,1966
10016,9946
133203
5292,5362
299369
457527
file = open ('input.csv','rb') fi = file.readlines() new_collect = [] final = [] for row in fi: row_new = row.rstrip().split(',') if row_new[1] > row_new[2]: new_collect = row_new[2] + ',' + row_new[1] final.append(new_collect) elif row_new[2] > row_new[1]: new_collect = row_new[2] + ',' + row_new[1] final.append(new_collect) fo = open('output.csv', 'wb') fo.write('\n'.join(final)+'\n') fo.close()但我的结果不正确。 结果不一致(第1栏>第2栏)。
有人可以帮忙吗? 否则更好的方法呢?
谢谢!
I have two columns' number and I would like to compare them. Then output file will be smaller one in Column 2 and larger one in Column 1.
For example, below is my XX.csv file.
c1,c2
1015,945
1028,958
1901,1966
10016,9946
133,203
5292,5362
299,369
457,527
file = open ('input.csv','rb') fi = file.readlines() new_collect = [] final = [] for row in fi: row_new = row.rstrip().split(',') if row_new[1] > row_new[2]: new_collect = row_new[2] + ',' + row_new[1] final.append(new_collect) elif row_new[2] > row_new[1]: new_collect = row_new[2] + ',' + row_new[1] final.append(new_collect) fo = open('output.csv', 'wb') fo.write('\n'.join(final)+'\n') fo.close()But my result was not correct. Results were not consistent (Column 1 > Column 2).
Anyone can help? Otherwise a better way to do so?
Thanks!
最满意答案
你的代码中的主要错误是你没有比较数字,而是字符串,所以“2”大于“10”。
我还有其他一些评论:
避免将file用作变量名,因为它是保留名称。 您可以在文件对象上使用“for”语句进行迭代,以便一次处理一行 当您访问文本文件时,应避免使用二进制模式 使用“with”语句确保文件正确关闭这是我提出的解决方案:
with open('input.csv', 'r') as ifile: with open('output.csv', 'w') as ofile: for line in ifile: try: c1, c2 = [int(val.strip()) for val in line.split(',', 1)] except ValueError: # skip malformed lines continue ofile.write("%s,%s\n" % ( (c1, c2) if c1 > c2 else (c2, c1)))The main mistake in your code is that you are not comparing numbers, but strings, so "2" is greater than "10".
I have some other remarks:
avoid using file as variable name as it's a reserved name. you can iterate with a "for" statement over a file object to proces a line at a time when you access text files you should avoid using binary mode use "with" statements to ensure the files are properly closingHere is my proposed solution:
with open('input.csv', 'r') as ifile: with open('output.csv', 'w') as ofile: for line in ifile: try: c1, c2 = [int(val.strip()) for val in line.split(',', 1)] except ValueError: # skip malformed lines continue ofile.write("%s,%s\n" % ( (c1, c2) if c1 > c2 else (c2, c1)))更多推荐
发布评论