0

I have two functions I have created as follows

def load_dates(stations):     
    f = open(stations[0] + '.txt', 'r')

    dates = []
    for line in f:
        dates.append(line.split()[0])
    f.close()
    return dates


stations = load_stations("stations.txt")
dates = load_dates(stations)

and

def load_station_data(station):

    f = open(stations[0] + '.txt', 'r')
    temp = []
    for line in f:
        x = (line.split()[1])
        x = x.strip()
        temp.append(x)
    f.close()
    return temp

The first function retrieves dates from a list in a seperate file (hence openfile function) which can be seen to be the first column and the second retrieves the temperatures whilst eliminating the spaces. The second function however goes and gets the temperatures from a specific file (station).

Dates       Temp

19600101    29.2
19600102    29.4
19600103    29.5

The question I have now is how I could make my new function display the list of data for temp inside a corresponding list for different station files

for example there is a list of temperatures that belong to every station(city). I know what I have to do is create an empty list keep iterating through the the stations using a for loop and then add what i iterated throughout the empty lists using the append function. I am new to python and so am struggling with the part said above

8
  • 1
    why not to use context manager with open? Commented Apr 15, 2015 at 8:24
  • can You provide sample output? Commented Apr 15, 2015 at 8:25
  • can you also provide a sample of the input file? Commented Apr 15, 2015 at 8:29
  • How is your file looks like? what is your expected output? Commented Apr 15, 2015 at 8:32
  • output of the function should appear as ([29.2, 29.4, 29.5], [xx.x, xx.x, xx.x]) where each list inside the main list represents a particular stations data. Commented Apr 15, 2015 at 8:36

3 Answers 3

2

Instead of using lists, it's better to use dictionnaries here.

#" = {}" create a dictionnary
cities = {}
#put the files you want to parse in this list
file_list = ("city1.txt", "city2.txt")
for file_name in file_list:
    file = open(file_name, 'r')
    #we don't want the .txt in the name, so we'll cut it
    #split splits the file_name into a list, removing all dots
    city_name = file_name.split('.')[0]
    #"= []" create an empty list
    cities[city_name] = []
    for line in file:
        #strip will remove all unnecessary spaces
        values = line.strip().strip(' ')
        #verify the length, we don't want to use empty lines
        if len(values) == 2:
            cities[city_name] = values[1]
    file.close()

I hope this will do what you want

Edit: All the cities and the values are now in the dictionnary 'cities', if you want to access a specific city's temps, you can do it like that

print(cities["cityname"])

and if you want to read all data, you can print the whole dict

for key, temperatures in cities.iteritems():
    print("City: " + key)
    for temperature in temperatures:
        print("\t" + temperature)
Sign up to request clarification or add additional context in comments.

2 Comments

would this work in python 3 ? thank you very much btw :)
I don't really know, I use python 2.7. The print at least will work, you may need to add parantheses to the for loops
2

agree with @Morb that a dict sounds more sensible but in answer to your original question you can certainly append a list to a list (as opposed to extend) So, say each line in your file was like:

19600101 29.2 28.4 25.6 30.2
19600102 26.2 24.4 21.6 30.5

you could

temp.append(line.split()[1:])

and end up with a list of lists

[['29.2', '28.4', '25.6', '30.2'],['26.2', '24.4', '21.6', '30.5']]

Comments

0

I am not sure I get the problem either, but maybe you should:

  • Do only one loop to get both temperature and date:

    def load_all_data(stations):
        f = open(stations[0] + '.txt')
        dates, temps = [], []
        for line in f.readlines():
            dates.append(line.split()[0])
            temps.append(line.split()[1].strip())
        f.close()
        return dates, temps
    
  • use list comprehension:

    def load_all_data(stations):
        f = open(stations[0] + '.txt'):
        dates = [line.split()[0] for line in f.readlines()]
        temps = [line.split()[1].split() for line in f.readlines()]
    f.close()
    return dates, temps
    
  • use context manager for open as suggested by cool_jesus:

    def load_data_all(stations):
        with open(stations[0] + '.txt') as f:
            dates = [line.split()[0] for line in f.readlines()]
            temps = [line.split()[1].split() for line in f.readlines()]
        return dates, temps
    
  • do a loop on stations :

    def load_data_all(stations):
        data_stations = [] 
        for station in stations:
            with open(station + '.txt') as f:
                dates = [line.split()[0] for line in f.readlines()]
                temps = [line.split()[1].split() for line in f.readlines()]
                data_stations.append((temps, dates))
        return data_stations
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.