Home > Enterprise >  Calculating from files in python
Calculating from files in python

Time:11-15

I have a file containing school codes and votes for different cities.

The file is like:

City: California
ADS, 532
SJD, 221
WPE, 239
City: Chicago
ADS, 238
SJD, 233
WPE, 456
...

My questions are

  1. How to add information to the file? Let's say, I want to add DJF, 204 for Chicago, how do I do that?

  2. How do I calculate the total of votes for each school code? Like for WPE for both Chicago and California?

I tried using dictionaries to make it easier, but I feel lost. Also, I set the code to add new info to the file, but I want to add it to a specific category and not just at the end of the file.

P.S. I'm a beginner so it's still a lot for me to process.

CodePudding user response:

Welcome to SO! To achieve what you want, you can basically create a nested dictionary with key and value pair. You can then access the first level of keys and add other information in file such as DJF for Chicago. Then, you can write that dictionary to a file as json object. To get the sum you can basically use sum function. Here is the code:

import json
dictForCities ={"California" : {"ADS" : 532, "SJD": 221, "WPE" : 239 }, "Chicago": {"ADS": 238, "SJD": 233, "WPE": 456}}
dictForCities["Chicago"]["DJF"] = 204
with open('test', 'w') as f:
    f.write(json.dumps(dictForCities))


# To get the total of votes 
sumForADS = sum(d['ADS'] for d in dictForCities.values() if d)
sumForWPE = sum(d['WPE'] for d in dictForCities.values() if d)
print(sumForADS)
print(sumForWPE)

Hope this helps!

CodePudding user response:

# start of temporary file read

data = '''City: California
ADS, 532
SJD, 221
WPE, 239
City: Chicago
ADS, 238
SJD, 233
WPE, 456'''

# change it to your file read method, e.g.:
# with open('data.txt','r') as f:
#     data = f.read()
#     ...
import tempfile
with tempfile.TemporaryFile(mode='w ') as fp:
    fp.write(data)
    fp.seek(0)
    data = fp.read()
# end of temporary file read
    
    lines = data.split('\n')
    cities = dict()
    last_city = None
    for line in lines: # you can use `for line in f:` if your file is big
        line = line.strip() # remove leading and trailing spaces
        if line.startswith('City:'): # is this line a city's name?
            last_city = line.removeprefix('City: ') # then save it without the `City: ` part
        elif last_city is not None: # do we have any city saved?
            name, value = line.split(',') # split line into a list: `ADS, 532` -> ['ADS', ' 532'], note the extra space before 532
            name = name.strip() # remove spaces
            value = int(value.strip()) # remove spaces and convert to integer
            values = cities.setdefault(last_city,dict()) # get the dictionary at key `last_city` or return a new one if it doesn't exist yet
            values[name] = value # add value to this dictionary, this is the same as the `cities[last_city]' so it will get added here too
            
# now we have our data structure filled with data from the file

# function to print cities
def print_cities(cities):
    for city,values in cities.items():
        print(city)
        for name,value in values.items():
            print(f'\t{name}: {value}')
    print('-'*16) # separator
    
#let's print it
print_cities(cities)

# add a new value to it
cities['Chicago']['DJF'] = 204

# let's print again, note that the DJF, 204 got added to Chicago
print_cities(cities)
        
# write to file
with open('output.txt','w') as f:
    for city,values in cities.items():
        f.write(f'City: {city}\n')
        for name,value in values.items():
            f.write(f'{name}, {value}\n')

I tried to explain every line, I also added a temporary file read, which you don't need, but as I don't have your file, and don't exactly know how it looks like, I copied the contents at the top and tried to emulate a file read. You can swap that part with a normal file read which I also added.

You need to read the file into a data structure, modify it's contents, then write it to a file.

  • Related