Python文件编写格式问题

时间:2014-10-15 23:44:25

标签: python-3.x

守则

def rainfallInInches():
file_object = open('rainfalls.txt')
list_of_cities = []
list_of_rainfall_inches = []

for line in file_object:
    cut_up_line = line.split()
    city = cut_up_line[0]
    rainfall_mm = int(line[len(line) - 3:])
    rainfall_inches = rainfall_mm / 25.4
    list_of_cities.append(city)
    list_of_rainfall_inches.append(rainfall_inches)

inch_index = 0
desired_file = open("rainfallInInches.txt", "w")
for city in list_of_cities:
    desired_file.writelines(str((city, "{0:0.2f}".format(list_of_rainfall_inches[inch_index]))))
    inch_index += 1
desired_file.close()

rainfalls.txt

Manchester 37
Portsmouth 9
London 5
Southampton 12
Leeds 20
Cardiff 42
Birmingham 34
Edinburgh 26
Newcastle 11

rainfallInInches.txt 这是不需要的输出

  

('曼彻斯特','1.46')('朴茨茅斯','0.35')('伦敦',   '0.20')('Southampton','0.47')('利兹','0.79')('加的夫',   '1.65')('伯明翰','1.34')('爱丁堡','1.02')('纽卡斯尔',   '0.43')

我的程序从'rainfalls.txt'获取数据,该数据具有以mm为单位的降雨信息,并将mm转换为英寸,然后将此新信息写入新文件'rainfallInInches.txt'。

我已经走到这一步了,除非我无法弄清楚如何格式化'rainfallInInches.txt'以使其看起来像'rainfalls.txt'。

请记住,我是一名学生,你可能是我的hacky代码收集的。

2 个答案:

答案 0 :(得分:1)

  

我的程序从'rainfalls.txt'获取数据,该数据具有以mm为单位的降雨信息,并将mm转换为英寸,然后将此新信息写入新文件'rainfallInInches.txt'。

您可以分离输入文件的解析,从mm到英寸的转换,以及写入的最终格式:

#!/usr/bin/env python
# read input
rainfall_data = [] # city, rainfall pairs
with open('rainfalls.txt') as file:
    for line in file:
        if line.strip(): # non-blank
            city, rainfall = line.split() # no comments in the input
            rainfall_data.append((city, float(rainfall)))

def mm_to_inches(mm):
    """Convert *mm* to inches."""
    return mm * 0.039370

# write output
with open('rainfallInInches.txt', 'w') as file:
    for city, rainfall_mm in rainfall_data:
        file.write("{city} {rainfall:.2f}\n".format(city=city,
            rainfall=mm_to_inches(rainfall_mm)))

rainfallInInches.txt

Manchester 1.46
Portsmouth 0.35
London 0.20
Southampton 0.47
Leeds 0.79
Cardiff 1.65
Birmingham 1.34
Edinburgh 1.02
Newcastle 0.43

如果您确信每个步骤都是孤立的,那么您可以结合以下步骤:

#!/usr/bin/env python
def mm_to_inches(mm):
    """Convert *mm* to inches."""
    return mm * 0.039370

with open('rainfalls.txt') as input_file, \
     open('rainfallInInches.txt', 'w') as output_file:
    for line in input_file:
        if line.strip(): # non-blank
            city, rainfall_mm = line.split() # no comments
            output_file.write("{city} {rainfall:.2f}\n".format(city=city,
                rainfall=mm_to_inches(float(rainfall_mm))))

It produces the same output

答案 1 :(得分:0)

首先,最好更改解析器以按空格分割字符串。有了这个,你不需要复杂的逻辑来获取数字。 在此之后,要正确打印,请将输出更改为

 file.write("{} {0:0.02f}\n".format(city,list_of_rainfall_inches[inch_index] ))