Python file writing format problem

advertisements

The Code

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 This is the unwanted output

('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')

My program takes the data from 'rainfalls.txt' which has rainfall information in mm and converts the mm to inches then writes this new information into a new file 'rainfallInInches.txt'.

I've gotten this far except I can't figure out how to format 'rainfallInInches.txt' to make it look like 'rainfalls.txt'.

Bear in mind that I am a student, which you probably gathered by my hacky code.


My program takes the data from 'rainfalls.txt' which has rainfall information in mm and converts the mm to inches then writes this new information into a new file 'rainfallInInches.txt'.

You could separate the parsing of the input file, the conversion from mm to inches, and the final formatting for writing:

#!/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

If you feel confident that each step is correct in isolation then you could combine the steps:

#!/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.