-1

a python program to read the rainfall.txt file and then write out a new file called rainfallfmt.txt . The data should be grouped on the total annual rainfall field into the following categories: [60-70], [71-80], [81-90],[91-]. Under each category, the new file should format each line so that the city is right-justified in a field that is 25 characters wide, and the rainfall data should be printed in a field that is 5 characters wide with 1 digit to the right of the decimal point. This is what I have so far; the problem is I don't know how to categorize it? Would you please help me and let me know how I can solve this problem?

================================================

 # read the rainfall.txt then write out a new file called rainfall.txt
    # the data should be grouped on the total annual rainfall field into the 
    # categories: [60-70], [71-80], [81,90], [91-]

        import os.path

        def main():
            endofprogram = False
            try:
                InputFileName = input('Enter name of input file: ')
                infile = open(InputFileName,'r')
                OutputFileName = input('Enter name of output file: ')
                # determine wether name exists
                while True:
                    if os.path.isfile(OutputFileName):
                        OutputFileName = input('File Exists. Enter name again: ')
                    else:
                        outfile = open(OutputFileName,'w')
                        break
            except IOError:
                print("Error opening file - End of program")
                endofprogram = True

                #If there is not exception, start reading the input file
                #Write the same data in formated form in new file.
                if endofprogram == False:
                    data = []
                    for line in infile:
                    .
                    .# I dont know what to do in here!
                    .
                    outfile.write(data[0])
        main()
  • 1
    Wellcome to SO. What have you tried so far? Check http://stackoverflow.com/help/how-to-ask. – Fernando Jan 14 '15 at 02:18
  • Thanks, Would you please help to solve this problem. I am a new learner in python. – PythonLearner Jan 14 '15 at 02:28
  • How is the format of the input file? – Fernando Jan 14 '15 at 02:28
  • it is txt, and here is its data: Akron 65.5574 Albia 95.631 Algona 77.9526 Allison 85.4456 Alton 69.6722 AmesW 86.5378 AmesSE 86.233 Anamosa 89.7382 Ankeny 84.7852 Atlantic 88.3158 Audubon 84.8614 Beaconsfield 89.5858 Bedford 92.329 BellePlaine 90.9574 Bellevue 87.249 Blockton 92.1512 Bloomfield 96.5708 Boone 92.202 Brighton 85.3186 Britt 80.1116 Buckeye 85.4964 BurlingtonKBUR 96.3676 Burlington 93.8276 Carroll 84.6582 Cascade 85.0392 – PythonLearner Jan 14 '15 at 02:30
  • Also, each data is in a separate line. – PythonLearner Jan 14 '15 at 02:31

2 Answers2

0

You can use split to separate the line in fields (it returns a list of strings), then take the rainfall, convert it to float, and use a list per category to store the data.

cat_60 = []
cat_71 = []
cat_81 = []
cat_91 = []
for line in infile:
    city, rain = line.split(' ')    # Spliting using blank as separator
    rain = float(rain)

    if 60 <= rain <= 70:            # This works in Python as expected but don't in most other languages
        cat_60.append((city, rain)) # Storing a tuple at the end of the list
    elif 71 <= rain <= 80:
        cat_71.append((city, rain))
    # etc...

After that you can iterate in the categories and format the output with str.format() or using the % operator.

There are other things you can do to make your code more Pythonic, for example variable names should be snakecase, names in titlecase should be reserved for classes and uppercase for constants and instead of using a flag variable you can use and exit() to end the program.

You can do the following to call main() only if the file is invoked as a script:

if __name__ == '__main__':
    main()
Fernando
  • 1,382
  • 8
  • 17
  • Thanks, :) But now the problem is that in my outputfile there is no data !? :( – PythonLearner Jan 14 '15 at 02:59
  • You shouldn't put that as an answer. Anyway your `if` is overindented, it is inside the `except` clause. – Fernando Jan 14 '15 at 03:05
  • Also in the invocations to `outfile.write` you have syntax errors, to save the content of the lists you have to traverse them and format its contents to a string using `str.format` or the `%` operator. – Fernando Jan 14 '15 at 03:10
  • I dont know what you mean by that ?! – PythonLearner Jan 14 '15 at 03:22
  • Thanks, I really appreciate for your time, I just figure it out, what was the problem. I will edit my answer and share it with everyone. thanks again. :) – PythonLearner Jan 14 '15 at 03:32
  • By traversing I mean that you have to iterate over each of the categories and use the data in each tuple to produce the string you will save on the output text file. To produce the string with the intended format check this related answer http://stackoverflow.com/questions/17091446/how-do-i-align-text-output-in-python – Fernando Jan 14 '15 at 03:33
0
# read the rainfall.txt then write out a new file called rainfall.txt
# the data should be grouped on the total annual rainfall field into the 
# categories: [60-70], [71-80], [81,90], [91-]
import os.path

def main():

    endofprogram = False
    try:
        InputFileName = input('Enter name of input file: ')
        infile = open(InputFileName,'r')
        OutputFileName = input('Enter name of output file: ')
        # determine wether name exists
        while True:
            if os.path.isfile(OutputFileName):
                OutputFileName = input('File Exists. Enter name again: ')
            else:
                outfile = open(OutputFileName,'w')
                break
    except IOError:
        print("Error opening file - End of program")
        endofprogram = True

        #If there is not exception, start reading the input file
        #Write the same data in formated form in new file.
    if endofprogram == False:
        cat_60 = []
        cat_71 = []
        cat_81 = []
        cat_91 = []
        for line in infile:
            city, rain = line.split(' ')
            rain = float(rain)

            if 60 <= rain < 70:            
                cat_60.append((city, rain)) # Storing a tuple in the list
            elif 70 <= rain < 80:
                cat_71.append((city, rain))  
            elif 80 <= rain < 90:
                cat_81.append((city, rain))
            elif 90 <= rain :
                cat_91.append((city, rain))

        outfile.write("[60-70]"+'\n')
        for i in range(len(cat_60)):
            city = cat_60[i][0]
            rain = cat_60[i][1]
            outfile.write('%+25s'%(city)+'%5.1f'%(rain)+'\n')

        outfile.write("[70-80]"+'\n')
        for i in range(len(cat_71)):
            city = cat_71[i][0]
            rain = cat_71[i][1]                
            outfile.write('%+25s'%(city)+'%5.1f'%(rain)+'\n')

        outfile.write("[80-90]"+'\n')
        for i in range(len(cat_81)):
            city = cat_81[i][0]
            rain = cat_81[i][1]
            outfile.write('%+25s'%(city)+'%5.1f'%(rain)+'\n')

        outfile.write("[91-]"+'\n')
        for i in range(len(cat_91)):
            city = cat_91[i][0]
            rain = cat_91[i][1]
            outfile.write('%+25s'%(city)+'%5.1f'%(rain)+'\n')
main()
  • The format string for either `format()` or `%` can have several conversions, usually you would write something like `'%+25s%5.1f\n' % (city, rain)` or the recommended way using `format()`: `'{:>25s}{:5.1f}\n'.format(city, rain)` – Fernando Jan 16 '15 at 00:27