Loading Python Files

Asked 2 years ago, Updated 2 years ago, 20 views

The code below is a program that reads the specified text file (ave.txt) and produces the average temperature.

Current State Code:

 path="ave.txt"
sum = 0.0
a = 0
with open(path, "r") as f:
    For lin f:
        l = l. strip()
        b=l.split(',')
        iflen(b) == 1:
            name = (b[0].strip('"')
        iflen(b) == 2:
            sum+=float(b[1].trip('"))
            a + = 1

The average temperature for print(f"{name} is {sum/a} degrees.")

ave.txt

"Tokyo"
"January", "-3.6"
"February", "-3.1"
"March", "0.6".
"April", "7.1".
"May", "12.4".
"June", "16.7".
"July", "20.5".
"August", "22.3".
"September", "1
"October", "11.8".
November, 4.9
"December", "-0.9"

It is a program that reads a file and produces an average temperature.
So if you look at the b of this expression, you'll see this:

b results:

['Tokyo']
["January", "-3.6"]
["February", "-3.1"]
["March", "0.6"]
["April", "7.1"]
["May", "12.4"]
["June", "16.7"]
["July", "20.5"]
["August", "22.3"]
["September", "18.1"]
["October", "11.8"]
["November", "4.9"]
["December", "-0.9"]

What should I do if I want to go from this state to the following state?

Expected results:

January: -3.6 degrees↩
February: -3.1 degrees ↩
March: 0.6 degrees ↩
April: 7.1 degrees ↩
May: 12.4 degrees ↩
June: 16.7 degrees ↩
July: 20.5 degrees ↩
August: 22.3 degrees ↩
September: 18.1 degrees ↩
October: 11.8 degrees ↩
November: 4.9 degrees ↩
December: -0.9 degrees ↩

I'd like to erase ''' and put : in place of ','.
Only the moon and temperature are displayed, not the first line of Tokyo.

python

2022-09-30 11:25

1 Answers

The extension is .txt, but the data content seems to follow the format CSV.

Rather than just using a number of basic lines, you might want to consider using the standard csv module.

You can do it like this.

import csv
path = 'ave.txt'
#### sum = 0.0
#### a = 0
with open(path, 'r', newline=', encoding='utf-8')ascsvfile:
    spamreader=csv.reader(csvfile, delimiter=',',quotechar='")
    name=next(spamreader)[0]
    For row inspamreader:
        #### sum+=float(row[1])
        #### a + = 1
        print(f'{row[0]}:{row[1]} degrees')

#### The average temperature for print(f"{name} is {sum/a} degrees.")

Comments are made in ### for the parts that are not required for the "Expected View Results" of the original source.
Also, the display results look like a full-width colon :, so print() specifies it.

encoding= should be modified according to the contents of the file.
delimiter= and quotechar= are the same as the default values, so you don't have to specify them, but short usage examples on the reference page: changed and used them, so I put them back in place.


2022-09-30 11:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.