格式化txt文件中的数据

时间:2016-12-02 16:37:37

标签: python file text string-formatting

我有txt文件,我想以某种方式从中生成一个字符串。例如,如果文件包含:

Num Date____ Bank Type_______ NCu CCu Buy___________ Sell__________
001 20161130 NLB_ individuals 840 USD 0001,074800000 0001,050800000
001 20161130 NLB_ individuals 826 GBP 0000,863900000 0000,839900000
001 20161130 NLB_ individuals 756 CHF 0001,094200000 0001,060200000
001 20161130 NLB_ individuals 191 HRK 0007,650800000 0007,420800000
001 20161130 NLB_ individuals 348 HUF 0315,890000000 0307,090000000
001 20161130 NLB_ individuals 941 RSD 0124,940000000 0121,140000000
001 20161130 NLB_ individuals 977 BAM 0001,985000000 0001,919000000
001 20161130 NLB_ individuals 807 MKD 0062,110000000 0060,290000000
001 20161130 NLB_ individuals 643 RUB 0071,939300000 0066,539300000
001 20161130 NLB_ individuals 203 CZK 0027,544000000 0026,544000000
001 20161130 NLB_ individuals 985 PLN 0004,509000000 0004,361000000
001 20161130 NLB_ individuals 975 BGN 0001,979000000 0001,925000000
001 20161130 NLB_ individuals 578 NOK 0009,247100000 0008,907100000
001 20161130 NLB_ individuals 752 SEK 0009,929000000 0009,609000000
001 20161130 NLB_ individuals 208 DKK 0007,552100000 0007,328100000
001 20161130 NLB_ individuals 036 AUD 0001,444400000 0001,400400000
001 20161130 NLB_ individuals 124 CAD 0001,452800000 0001,404800000
001 20161130 NLB_ individuals 392 JPY 0121,830000000 0118,030000000

代码会产生以下内容:

GBP......0.8639......0.8399
USD......1.0748......1.0508
RUB.....71.9393.....66.5393
HRK......7.6508......7.4208
HUF....315.8900....307.0900

依此类推所有货币。

1 个答案:

答案 0 :(得分:0)

您的文本文件似乎使用固定格式,因此以下类型的方法应该有效:

fields = [slice(34, 37), slice(38, 52), slice(53, 67)]

with open('input.txt') as f_input, open('output.txt', 'w') as f_output:
    header = next(f_input)

    for row in f_input:
        cols = [row[field] for field in fields]
        cols[1] = '{:.>12.4f}'.format(float(cols[1].replace(',', '.')))
        cols[2] = '{:.>12.4f}'.format(float(cols[2].replace(',', '.')))
        f_output.write(''.join(cols) + '\n')

给你以下输出:

USD......1.0748......1.0508
GBP......0.8639......0.8399
CHF......1.0942......1.0602
HRK......7.6508......7.4208
HUF....315.8900....307.0900
RSD....124.9400....121.1400
BAM......1.9850......1.9190
MKD.....62.1100.....60.2900
RUB.....71.9393.....66.5393
CZK.....27.5440.....26.5440
PLN......4.5090......4.3610
BGN......1.9790......1.9250
NOK......9.2471......8.9071
SEK......9.9290......9.6090
DKK......7.5521......7.3281
AUD......1.4444......1.4004
CAD......1.4528......1.4048
JPY....121.8300....118.0300

这使用slice个对象列表来保存字段每行的位置。这些是使用列表理解提取的。然后将第2列和第3列转换为浮点数,并使用前导点和四个小数位进行格式化。然后将结果列表写出到文件中。