我正在使用Python 2.7.9。我正在研究一个程序,它应该在每个循环的.csv文件中产生以下输出:
URL,number
这是我正在使用的代码的主循环:
csvlist = open(listfile,'w')
f = open(list, "r")
def hasQuality(item):
for quality in qualities:
if quality in item:
return True
return False
for line in f:
line = line.split('\n')
line = line[0]
# print line
itemname = urllib.unquote(line).decode('utf8')
# print itemhash
if hasQuality(itemname):
try:
looptime = time.time()
url = baseUrl + line
results = json.loads(urlopen(url).read())
# status = results.status_code
content = results
if 'median_price' in content:
medianstr = str(content['median_price']).replace('$','')
medianstr = medianstr.replace('.','')
median = float(medianstr)
volume = content['volume']
print url+'\n'+itemname
print 'Median: $'+medianstr
print 'Volume: '+str(volume)
if (median > minprice) and (volume > minvol):
csvlist.write(line + ',' + medianstr + '\n')
print '+ADDED TO LIST'
else:
print 'No median price given for '+itemname+'.\nGiving up on item.'
print "Finished loop in " + str(round(time.time() - looptime,3)) + " seconds."
except ValueError:
print "we blacklisted fool?? cause we skippin beats"
else:
print itemname+'is a commodity.\nGiving up on item.'
csvlist.close()
f.close()
print "Finished script in " + str(round(time.time() - runtime, 3)) + " seconds."
应该生成一个如下所示的列表:
AWP%20%7C%20Asiimov%20%28Field-Tested%29,3911
M4A1-S%20%7C%20Hyper%20Beast%20%28Field-Tested%29,4202
但实际生成一个如下所示的列表:
AWP%20%7C%20Asiimov%20%28Field-Tested%29
,3911
M4A1-S%20%7C%20Hyper%20Beast%20%28Field-Tested%29
,4202
每当在Windows机器上运行时,我都没有问题。然而,每当我在我的EC2实例上运行它时,它都会添加额外的换行符。有什么想法吗?在文件上运行命令,如
awk 'NR%2{printf $0" ";next;}1' output.csv
什么都不做。我已将其转移到我的Windows机器上,它仍然会读取相同内容。但是,当我将输出粘贴到Steam的聊天客户端时,它会以我想要的方式连接它。
提前致谢!
答案 0 :(得分:1)
这是问题发生的地方
<强>码强>
csvlist.write(line + ',' + medianstr + '\n')
这可以清除你剥离空间
修改后的代码:
csvlist.write(line.strip() + ',' + medianstr + '\n')
<强>问题:强>
问题是由you are reading raw lines from the input file
Raw_lines包含\n
,表示每一行都有一个新行,它不是最后一行,最后一行是以给定字符结尾。
了解更多详情:
Just type print(repr(line)) before writing and see the output