cdp_data.csv
1
2
3
4
所以我正在制作这个csv处理器。当我在Windows上编译它时没有","在csv内的行尾。但是当我在服务器上运行时,有一个额外的","在线。他们有相同的python版本。
#!/usr/bin/python
import re
import datetime
now = datetime.datetime.now()
day_minus_one = now + datetime.timedelta(days=-1)
new_date = day_minus_one.strftime('%Y%m%d')
f = open('/tmp/cdp_data.csv','rb')
fo = open('/tmp/cdp_out.csv','wb')
fo.writelines("{},".format(new_date))
for line in f:
bits = line.split(',')
bits[0] = re.sub(r'\n', ",", bits[0])
bits[0] = re.sub(r'\r', "", bits[0])
fo.write( ','.join(bits) )
f.close()
fo.close()
Windows结果:
20170329,1,2,3,4
Linux结果:
20170329,1,2,3,4,
答案 0 :(得分:0)
如果您确实要对CSV进行硬编码,请使用bits = line.strip().split(',')
。 strip()
方法删除尾随空格,并删除列表末尾的空字符串。
否则,建议的方法是使用csv模块自动处理所有读取,写入和解析。
import csv
with open('/tmp/cdp_data.csv', newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
with open('/tmp/cdp_out.csv', 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for row in spamreader:
spamwriter.writerow(row)