2012-05-27 7 views
0

CSV 파일을 가져 오는데 가격 중 하나에 0이 누락되었습니다.숫자를 달러 형식으로 변환하는 파이썬

원하는 출력 : 12.10

전류 출력을 : 12.1

어떻게 내가 영을 적용 할 것입니다 내 데이터에 포함되는? 내가 지금까지했던 어떤

:

#!/usr/bin/python 

import csv 
import sys 
import argparse 

#parsing command line options 
parser = argparse.ArgumentParser(prog='desc', description=__doc__) 
parser.add_argument('-i', '--input', help='Input file', nargs='?', type=argparse.FileType('r'), default=sys.stdin) 
parser.add_argument('-o', '--output', help='Output file', nargs='?', type=argparse.FileType('w'), default=sys.stdout) 
args = parser.parse_args(sys.argv[1:]) 
inf, outf = args.input, args.output 
outf = csv.writer(outf) 

print 'Loading %s file into memory' % inf.name 
data = [] 
tmp = 0.00 
for i, line in enumerate(csv.reader(inf)): 
    if i == 0: 
     outf.writerow(line) 
     continue 
    price = line[4] 
    price = price.replace('.', '') 
    # print price 
    if (price < 100): 
     tmp = price 
     tmp = tmp * 10 
     print tmp 

답변

4

Format :

>>> '{:.2f}'.format(12.1) 
'12.10' 

PS : 당신은 당신의 csv 파일의 헤더를 건너 뛰고 등을 재 작성 무거운 enumerate 기능을 사용할 필요가 없습니다 출력에. 당신은 단순히 직접 첫 번째 라인을 작성할 수 있습니다

csvin = csv.reader(inf) 
outf.writerow(csvin.next()) # header line 1 
for line in csvin: # iterator goes on from line 2 
    price = line[4] 
    #... 
+0

소수점 이하 두 자리로 변수를 저장할 수 있습니까? 매번 libreoffice와 같은 CSV 프로그램에서 열면 마지막 0이 사라집니다. – chrisjlee

+0

Excel 또는 LibreOffice로 CSV 생성 파일을 열면 파일을 해석하고 스프레드 시트에서 후미 0이 사라집니다. 뒤에 오는 0을 유지하려면 엑셀 파일이나 odf 문서를 직접 생성해야합니다 – Boud

3

두 가지 옵션 :

  1. 사용 유형 소수점 이하 자릿수가 문제 등 decimal.Decimal있다.

  2. 지금은 무시하고 출력시 %.2f과 같이 소수점 두 자리를 지정하는 형식을 사용하십시오. 이 개 소수의 문자열로 당신의 플로트

2

대신

print tmp 

의이 두 소수점 이하 자릿수로 포맷 할 수있는 플로트를 강제

print '{0:.2f}'.format(tmp) 

을 시도합니다.

1
>>> price=12.10 
>>> price 
12.1 
>>> print('{0:.2f}'.format(price)) 
12.10 
+0

그러면 다음과 같은 오류가 발생합니다 : 'ValueError :'str '유형의 객체에 대해 알 수없는 형식 코드'f ' – chrisjlee

+0

'if (price <100) : 문자열을 int 객체와 비교하려고합니까? 먼저'float()'또는'int()'로 변환하면 오류가 발생합니다. –

+0

아하이 봐요. 고맙습니다. – chrisjlee

관련 문제