Code not writing output to file [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 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()

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)

Convert text file into dictionary [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 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

how to store a dictionary as a json file and edit it? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a function that creates a dictionary based on the user's input:
def store_data(user_inp):
list_of_letters = list(user_inp)
list_of_colons = []
nested_dict = {}
for letter in list_of_letters:
if letter == ':':
list_of_colons.append(letter)
if len(list_of_colons) == 2:
str1 = ''.join(list_of_letters)
list2 = str1.split(':')
main_key = list2[0]
nested_key = list2[1]
value = list2[2]
if main_key not in storage:
storage[main_key] = nested_dict
nested_dict[nested_key] = value
print(storage, '\n', 'successfully saved!')
elif main_key in storage:
if nested_key in storage[main_key]:
print('this item is already saved: \n', storage)
else:
storage[main_key][nested_key] = value
print(storage, '\n', 'successfully saved!')
jf = json.dumps(storage)
with open('myStorage.json', 'w') as f:
f.write(jf)
f.close()
What i'm trying to do is to store the final dictionary somewhere permanent.
I tried this at the end of my function but it doesn't seem to work:
jf = json.dumps(storage)
with open('myStorage.json', 'w') as f:
f.write(jf)
f.close()
How can I store the final dictionary so it's permanent but still editable?
You can save it to a .json file as you did. After that, you can still edit the variable that you pasted. So you could create a thread that auto-saves every 10 minutes or so by invoking
jf = json.dumps(storage)
with open('myStorage.json', 'w') as f:
f.write(jf)
PS: You don't need to care about f.close() if you are using with open(...) :)
If you can't tell what is happening where I highly suggest printing the current state of storage before entering a new if clause
I'm sorry but I am unable to debug your code because there are to many variables undefined...

How to solve a TypeError: 'str' object is not callable? [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
CODE:
import csv
import sys
def costo_camion(costo_camion): #def es la palabra reservada
suma = 0
f = open('Data/camion.csv', 'rt')
headers = next(f).split(',')
for line in f:
row = line.split(",")
costo = float(row[2]) * int(row[1])
suma = suma + costo
f.close()
return(suma)
if len(sys.argv) == 2:
costo_camion = sys.argv[1]
else:
costo_camion = 'Data/camion.csv'
suma = costo_camion('Data/camion.csv')
print('Costo Total', suma)
Line
else:
costo_camion = 'Data/camion.csv')
shows up the type error 'str' object is not callable (Python) and I don't know why, the code without this part:
if len(sys.argv) == 2 etc works just fine
thanks**
On line 3 in your code, you name your function costo_camion:
...
def costo_camion(costo_camion):
...
Then, on either line 15 or 17 you initialize a variable also named costo_camion:
...
costo_camion = sys.argv[1]
...
costo_camion = 'Data/camion.csv'
On line 19, you then try to call the function costo_camion:
...
suma = costo_camion('Data/camion.csv')
...
This will give you an error, because by this point no such function exists -- you have overwritten that name by using it for your variable.
My suggestion: re-name the variable on lines 15 and 17 to something like costo_camion_filepath. After that, you should no longer get this error. (You might have other issues with this code, but this particular error should be gone. :) )

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))

Categories