0

I'm making a dictionary (in python) of a text file that is on the format:

type_of_animal / hibernation / wake_up_time / sleep_time / feeding_time

with a new type of animal on every new line. This is the code so far:

def read_animals_from_file(file_name):

'''
Makes a dictionary with the animals as keys and their attributes as values
:param file_name: Name of the file with information
:return: Dictionary with the animals and their attributes
'''

fobj = open(file_name, "r")
for line in fobj:
    key , value1 , value2 , value3 , value4 = line.split("/")

    animal_dict[key] = value1, int(value2), int(value3), value4

print(animal_dict)
return animal_dict

The problem is that the last value of the each line contains "\n". This is what the dictionary looks like:

{'Bear ': (' winter ', 9, 20, ' 12\n'),

'Bumblebee ': (' winter ', 6, 23, ' -\n'),

'Moose ': (' - ', 7, 19, ' 10'),

'Owl ': (' - ', 21, 5, ' 21\n'),

'Sea lion ': (' - ', 6, 18, ' 14\n'),

'Seal ': (' - ', 6, 18, ' 14\n'),

'Wolf ': (' - ', 6, 20, ' 12\n')}

I'm thinking that I should strip \n before I create the dictionary, but I can't seem to make it work. I'm also curious to how I would access a specific value, since I think they are in what's called a tuple (?). For example, how would I do if I only wanted to print the wake up time? I apologize for possible beginner mistakes :)

mat3ilda
  • 3
  • 3
  • 1
    "I can't seem to make it work". What did you try? It should just be `line.strip().split("/")` in place of your existing split. You access values in a tuple via their index: `animal_dict['Bear '][0]` would be " winter " for example. Looking at the strings you have (with extra spaces everywhere), you might want to do a strip on each value rather than the whole line, e.g. `k, v1, v2, v3, v4 = [x.strip() for x in line.split("/")]`. – Kemp Apr 01 '21 at 15:21
  • Thanks for your help! As I said , I'm a complete beginner (idiot?) and tried line.strip(r"\n").split("/") as I've never used strip before. – mat3ilda Apr 01 '21 at 15:29
  • just use line.strip() alone see : https://stackoverflow.com/questions/13013734/string-strip-in-python :.strip() with no arguments (or None as the first argument) removes all whitespace at the start and end, including spaces, tabs, newlines and carriage returns. Leaving it in doesn't do any harm, and allows your program to deal with unexpected extra whitespace inserted into the file. – pippo1980 Apr 01 '21 at 17:55

0 Answers0