Convert text file into dictionary [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I want to turn a txt file with this format:
valido;válido
invalidos;inválidos
avaliacao;avaliação
nao e;não é
into this with Python:
{'valido': 'válido', 'nao e': 'não é', 'invalidos': 'inválidos', 'avaliacao': 'avaliação'}
My code so far:
final = []
with open("fich_teste.txt", 'r') as file:
for line in file:
key; value = linha.sprit().split(';')
final[key] = value
return final
This returns an error:
builtins.NameError: global name 'key' is not defined

You need to assign values using key, value not key; value and fix some indentation problems along with the final declaration and method name:
def myFunc():
final = {}
with open("fich_teste.txt", 'r') as file:
for line in file:
key, value = line.strip().split(';')
final[key] = value
return final

Related

AttributeError: 'str' object has no attribute 'write json [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
import json
print(f"Enter some numbers")
userWD = input("--->")
with open("./Users/" + "test" + ".json", "r") as userID:
tmp = json.load(userID)
tmpBalance = tmp['Balance']
with open("./Users/" + "test" + ".json", "w") as f:
newBalance = int(tmpBalance) - int(userWD)
json.dump(newBalance, tmpBalance)
When i run this code , im getting this error: AttributeError: 'str' object has no attribute 'write'
Can someone tell me what is wrong?
You're trying to dump to tmpBalance (which is a string):
json.dump(newBalance, tmpBalance)
You want to dump into the file:
json.dump(newBalance, f)
After you're done with the calculation, newBalance is just a number. If you want to retain the complete data structure {"Balance": 12345}, you need to assign the new balance value back tmp:
tmp['Balance'] = newBalance
and then write tmp to the file, instead of newBalance.
I would re-arrange things like so:
import json
account_file = "./Users/test.json"
with open(account_file, "r") as f:
account = json.load(f)
print(f"Your account balance: {account['Balance']}.")
wd_amount = input("How much do you want to withdraw? >")
account['Balance'] -= int(wd_amount)
with open(account_file, "w") as f:
json.dump(account, f)

how to denote function arguments in python [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I need to print following info using unnecessary argument (track):
def make_album(singer, album, track = ''):
album = {'singer_name' : singer, 'slbum' : album}
if track:
album['track'] = track
return album
output = make_album('Linkin Park', 'October')
print(output)
output = make_album('Lara Fabian', 'Ju\'tem', 13)
print(output)
output = make_album('Space Girls', 'Viva')
print(output)
But the output is kind of
None
{'singer_name': 'Lara Fabian', 'slbum': "Ju'tem", 'track': 13}
None
How to denote args to avoid none output
you have a return in your function only if your track argument is not an empty string otherwise your function returns None to fix you can use:
def make_album(singer, album, track = ''):
album = {'singer_name' : singer, 'slbum' : album}
if track:
album['track'] = track
return album

Python 3 returning dictionary from a function case [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have python function that should return diction:
def load_cred(FILE):
key_for_enc = getpass(prompt='Key for encrypted credentials file: ', stream=None)
cipher = AESCipher(key_for_enc)
crd_dict={}
with open(FILE, 'r') as fh:
for line in fh:
dec_line = cipher.decrypt(line)
# print("line: {}".format(dec_line))
dec_line.strip()
start_string, user, password = dec_line.split(10*'|')
crd_dict[start_string] = (user, password)
#print("1: {} 2: {} 3: {}".format(start_string,user,password))
print("crd diction: {}".format(crd_dict))
return crd_dict
but when I call it from other script like that:
Data_cred = load_cred(CRED_FILE)
print ("Data type: {}".format(type(Data_cred)))
print("Data: ".format(Data_cred))
The returned dictionary don't appear as a returned value... Could anybody help me with this? Notice that within the function load_cred , crd_dict have it's items.. but outside it doesn't. I still don't get it why..
Key for encrypted credentials file:
crd diction: {'first_line': ('User1', 'Pass1')}
Data type: <class 'dict'>
Data len:
Data:
The function load_cred() is returning the dictionary. You just forgot to add the replacement field in the last line when printing it. -
print("Data: {}".format(Data_cred))

Coding a parser in Python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to make a config reader in Python. The config has the following structure:
#section:
property = 'value'
end
#section2:
property2 = 'value'
end
The config is managed using two functions:
getValue(file, section, property)
setValue(file, section, property, newvalue)
But I don't know how to do the parser. Help plz :\
That was interesting. This should work perfectly. I wasn't sure whether to strip out the single quotes you had next to your values, but I decided to take them out for cleanliness of output.
with open('configfile.cfg') as f:
data = f.readlines()
config = {}
current_section = None
for line in data:
line = line.strip()
if line == 'end' or not line:
continue
if line.startswith('#'):
current_section = line[1:-1]
config[current_section] = {}
else:
key, value = line.split('=')
config[current_section][key.strip()] = value.strip().strip("'")
print(config)
For future reference, it's a lot easier to help if you give a small bit of actual data and then describe the data, rather than giving names that are types. For example, I used this as a config file:
#section:
red = '3three'
end
#section2:
blue = '4four'
green = '5five'
end
and here's the output dict for that config file:
{'section': {'red': '3three'}, 'section2': {'blue': '4four', 'green': '5five'}}

Code not writing output to file [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
This code is not writing the output to the file. It only dumps the data in the .data file not the output which should be a range from 0 to 1.
import math
f = open('numeric.sm.data', 'r')
print f
maximum = 0
# get the maximum value
for input in f:
maximum = max(int(input), maximum)
f.close()
print('maximum ' + str(maximum))
# re-open the file to read in the values
f = open('numeric.sm.data', 'r')
print f
o = open('numeric_sm_results.txt', 'w')
print o
for input in f:
# method 1: Divide each value by max value
m1 = float(input) / (maximum)
o.write(input)
print repr(input.strip('\n')).rjust(5), repr(m1).rjust(5)
o.close()
f.close()
o.write(input)
should be
o.write(str(m1))
and probably you want to add a newline or something:
o.write('{0}\n'.format(m1))
It's because You have file handler called f
but it just points to an object, not the contents of your file
so,
f = open('numeric.sm.data', 'r')
f = f.readlines()
f.close()and then,
and then,
o = open('numeric_sm_results.txt', 'w')
for input in f:
# method 1: Divide each value by max value
m1 = float(input) / (maximum)
o.write(input) # Use casting if needed, This is File write
print repr(input.strip('\n')).rjust(5), repr(m1).rjust(5) # This is console write
o.close()

Categories