AttributeError: 'str' object has no attribute 'write json [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
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)

Related

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

AttributeError: 'function' object has no attribute 'save' - Python PIL QR Code not saving [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'm a newcomer to programming so i apologize for my lack of technical ability.
I'm trying to create a qrcode generator in python, however, when i try to increment the number on the filename save, i get this error.
Traceback (most recent call last):
File "/home/sam/Desktop/QR Code Gen/run.py", line 52, in <module>
purchase_code_fn()
File "/home/sam/Desktop/QR Code Gen/run.py", line 32, in purchase_code_fn
qr_code_fn()
File "/home/sam/Desktop/QR Code Gen/run.py", line 41, in qr_code_fn
im.save("filename"+ count + ".png")
AttributeError: 'function' object has no attribute 'save'
>>>
Is there anyway to rectify this?
(see below for my full code - it's still a WIP)
from qrcode import *
import csv
import time
active_csv = csv.writer(open("active_codes.csv", "wb"))
void_csv = csv.writer(open("void_codes.csv", "wb"))
active_csv.writerow([
('product_id'),
('code_id'),
('customer_name'),
('customer_email'),
('date_purchased'),
('date_expiry')])
void_csv.writerow([
('code_id'),
('customer_email'),
('date_expiry')])
count = 0
def purchase_code_fn():
global count
count =+ 1
customer_email = raw_input("Please enter your email: ")
product_id = raw_input("Which product would you like (1 - 5): ")
qr_code_fn()
def qr_code_fn():
qr = QRCode(version=5, error_correction=ERROR_CORRECT_M)
qr.add_data("asaasasa")
qr.make() # Generate the QRCode itself
# im contains a PIL.Image.Image object
im = qr.make_image
im.save("filename"+ count + ".png")
def restart_fn():
restart_prompt = raw_input("Would you like to purchase another code? : ").lower()
if restart_prompt == "yes" or restart_prompt == "y":
purchase_code_fn()
elif restart_prompt =="n" or restart_prompt == "no":
print("exit")
purchase_code_fn()
The error is here : im = qr.make_image. You are storing into im the function make_image of object qr. As you can store functions in variables in Python, this is a valid syntax.
So, you are not calling the function make_image, just storing it. It should be im = qr.make_image().
After you'll implement T. Claverie answer - it is likely that you'll fail in .save() as you are concating string and integer.
Can you try to change the following line:
im.save("filename"+ count + ".png")
to be:
im.save("filename"+ str(count) + ".png")

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

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

Python TypeError: unsupported operand types for +: 'tag' and 'str' [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 8 years ago.
Improve this question
I am using numbers from a specific column of an excel document(csv) to populate a URL, from which cURL extracts XML and places into a new column of the outfile (also an excel document). This process is repeated for each id in the column. I cannot figure out why I am getting this error, as the output is in fact a string, and I do not see why you would not be able to concatenate it with a 'tab' buffer. I also thought I should ask this since I did not see any other questions relating this error to tags, maybe someone else can benefit from it as well. Anyway here is some code let me know if more information is needed, I have marked where the error happens (near the bottom):
outFile = open(tempFileName, 'w')
outFile.write('\t'.join(fancyHeaders) + '\n')
outFile.write('\t'.join(order) + '\n')
lastFN = False
for line in data:
if lastFN!=line['AppStatus'] and lastFN:
outFile.write('\n')
for column in order:
outFile.write(line[column] + '\t') #Error occurs here
lastFN = line['AppStatus']
outFile.write('\n')
xlApp.Workbooks.OpenText(tempFileName)
xlApp.Range("A1:Z9999").HorizontalAlignment = -4131
xlApp.Range("A1:Z9999").VerticalAlignment = -4160
xlApp.Range("A1:Z9999").WrapText = True
xlApp.Cells.RowHeight=12.75
xlApp.DisplayAlerts=False
xlApp.ActiveWorkbook.SaveAs(outFileName)
xlApp.Quit()
xlApp.Visible = 0 # see note 2
del xlApp
if the line[column] is not string, you cannot concatenate it, then try to change:
str(line[column] + '\t')
into:
str(line[column]) + '\t'
Couldn't you just write it that way ?
outFile.write(str(line[column]) + '\t')

Categories