I tried some solutions from the internet but every time I get an error:
TypeError: write() argument must be str, not function
Here is my code:
import requests
import json
from pprint import pprint
# from datetime import datetime
def createParamsByUser(amount, typeOfAnimal):
params = { "amount" : amount, "animal_type" : typeOfAnimal}
return params
def listToStr(s):
str1 = ""
return (str1.join(s))
typeOfAnimal = input("Would you read facts about cat or dog?\n")
amount = str(input("How many facts would you generate?\n"))
createdParams = createParamsByUser(amount, typeOfAnimal)
r = requests.get("https://cat-fact.herokuapp.com/facts/random", createdParams)
s = []
try:
content = r.json()
except json.decoder.JSONDecodeError:
print("Wrong format")
else:
for animal in content:
pprint(animal["text"])
s.append(animal["text"])
printInToFile = input("Do you want print text above in to a file (type Y/N)")
if (printInToFile == "y" or "Y"):
with open("Facts about", "a+", encoding="UTF-8") as file:
file.write(listToStr)
elif (printInToFile == "n" or "N"):
print("Thanks for using my program")
By the way, how to write code to write datetime.today in front of the file name using datetime.today? I tried this:
with open(datetime.today + "Fact about" + typeOfAnimal , "a+", encoding="UTF-8") as file:
The problem is in this part:
if (printInToFile == "y" or "Y"):
with open("Facts about", "a+", encoding="UTF-8") as file:
file.write(listToStr)
elif (printInToFile == "n" or "N"):
print("Thanks for using my program")
In the write()
function, you are giving listTostr
as the argument, which is a function object, replace that with listToStr(<whatever parameters>)
.
if (printInToFile == "y" or "Y"):
with open("Facts about", "a+", encoding="UTF-8") as file:
file.write(listToStr(parameters))
elif (printInToFile == "n" or "N"):
print("Thanks for using my program")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.