我正在尝试用小数点替换逗号,然后用CSV文件中的逗号替换分号。
CSV文件:
# 2018-03-16: ECarbix Prices/Volumes for Emission Spot Market
#
# Data type(ST);Trading Date;Creation Time
# Data type(IL);Index;Unit;Price;Volume
# Data type(AL);Number of Lines
#
ST;2018-03-16;2018-03-19T08:39:48+01:00
IL;Day;EUR/tCO2;10,97;4533000
AL;9
我试过的代码:
import pandas as pd
from os import walk
import csv
import xml.dom.minidom
from xml.etree import ElementTree
with open('some.csv', 'w', newline='') as fw:
writer = csv.writer(fw)
for filenames in walk("D:\EEX_EMS\CSV"):
(filenames)
fname= list(filenames)
for f in fname[2]:
if "Auction" not in f:
#print(f)
with open('D:/EEX_EMS/CSV/'+f, 'r') as csvfile:
spamreader = csv.reader(csvfile, quotechar='|')
for fg in spamreader:
fi =str(fg)
print(fi)
fi1 = str(fi.replace(',','.'))
fi2 = str(fi1.replace(';',','))
fi_list =str(fi2.split(','))
print (str(fi_list))
writer.writerow(fi_list)
fw.close()
这是输出:
['# 2018-03-16: ECarbix Prices/Volumes for Emission Spot Market']
['# ']
['# Data type(ST),Trading Date,Creation Time']
['# Data type(IL),Index,Unit,Price,Volume']
['# Data type(AL),Number of Lines']
['# ']
['ST,2018-03-16,2018-03-19T08:39:48+01:00']
['IL,Day,EUR/tCO2,10'. '97,4533000']
['AL,9']
如何获得正确的输出?
答案 0 :(得分:0)
进行所需转换的一种方法是:
def convert_comma_number(maybe_number):
try:
return float(maybe_number.replace(',', '.'))
except ValueError:
return maybe_number
import csv
with open('csvfile.csv', 'rU') as f:
reader = csv.reader(f, delimiter=';')
for row in reader:
row = [convert_comma_number(col) for col in row]
print(row)
['# 2018-03-16: ECarbix Prices/Volumes for Emission Spot Market']
['# ']
['# Data type(ST)', 'Trading Date', 'Creation Time']
['# Data type(IL)', 'Index', 'Unit', 'Price', 'Volume']
['# Data type(AL)', 'Number of Lines']
['# ']
['ST', '2018-03-16', '2018-03-19T08:39:48+01:00']
['IL', 'Day', 'EUR/tCO2', 10.97, 4533000.0]
['AL', 9.0]