Rebagliati Loris
Rebagliati Loris

Reputation: 579

Write an integer or boolean value in text files

I have this function contained in a class:

def new_config(self):
    dict_dat = {"Display Set": self.main.id[20], "Display Width": self.main.id[4], "Display Height": self.main.id[5],
                "Fullscreen": self.main.id[9], "Music Volume": self.main.id[11], "Sound Volume": self.main.id[13],
                "Voice Volume": self.main.id[15], "Ambient Volume": self.main.id[17], "Other Volume": self.main.id[19]}
    cgo = open(self.path, "w")
    for name, dat in dict_dat.items():
        cgo.write(name + ":" + dat)
    cgo.close()

In the various "self.main.id" contains Integer and Boolean values. I would like to know how I can write in a text file, line by line, the value name (example "Display Set") and the value (self.main.id [20]), without having to convert everything into a string.

As I wrote above, I get the error: TypeError: Can't convert 'int' object to str implicitly The fact, however, is that if possible, I would like to write data without having to convert it.

With another file I used the Pickle module, but reading the file by opening it manually, it is unreadable for any person, so it makes it useless in this case.

Upvotes: 0

Views: 3696

Answers (5)

Veky
Veky

Reputation: 2745

As I said before, you can just print to a file.

def new_config(self):
    dict_dat = {
        'Display Set': 20, 
        'Display Width': 4, 
        'Display Height': 5,
        'Fullscreen': 9,
        'Music Volume': 11,
        'Sound Volume': 13,
        'Voice Volume': 15, 
        'Ambient Volume': 17, 
        'Other Volume': 19,
    }
    with open(self.path, 'w') as cgo:
        for name, idx in dict_dat.items():
            print(name, self.main.id[idx], sep=':', file=cgo)

Upvotes: 2

Laurent H.
Laurent H.

Reputation: 6526

A smart solution for you would be to use f-strings, available in Python 3.6+, as follows:

def new_config(self):
    dict_dat = {"Display Set": self.main.id[20], "Display Width": self.main.id[4], "Display Height": self.main.id[5], "Fullscreen": self.main.id[9], "Music Volume": self.main.id[11], "Sound Volume": self.main.id[13], "Voice Volume": self.main.id[15], "Ambient Volume": self.main.id[17], "Other Volume": self.main.id[19]}
    with open(self.path, 'a+') as f:
        for name, dat in dict_dat.items():
            f.write(f'{name}:{dat}\n')

If dat is a boolean True or False, it writes "True" or "False".
If dat is an integer, it writes the integer value.

Note 1: I also strongly recommend you to use with ... as ... statement, which automatically and properly closes the file at the end of the block.
Note 2: Unfortunately I have finally learnt that you were using Python 3.4. So this solution is not relevant for you (you get a syntax error on f-string). You can either upgrade to 3.6+ or replace the f-string with '{0}:{1}\n'.format(name, dat).

Upvotes: 2

Raviteja Ainampudi
Raviteja Ainampudi

Reputation: 282

Per write() method of Open() built-in function. Please check the documentation. - f.write(string) writes the contents of string to the file, returning the number of characters written. To write something other than a string, it needs to be converted to a string first.

https://docs.python.org/3.3/tutorial/inputoutput.html

You can change your code in this way.

file.write(str(name) + ":" + str(dat) + "\n")

Upvotes: 1

David Zemens
David Zemens

Reputation: 53623

Take advantage of the string.format method:

file.write('{0}:{1}\n'.format(name, dat))

enter image description here

Upvotes: 1

matejcik
matejcik

Reputation: 2072

Consider using JSON:

import json

# write your dict
with open(self.path, "w") as file:
    json.dump(dict_dat, file)

# read it back
with open(self.path) as file:
    loaded_dict = json.load(file)

Upvotes: 1

Related Questions