Reputation: 165
I am doing some online tutorials with python 3.5 and have learned how to write a string to a file and save it. Now I am trying to write the contents of a function but don't have any luck.
from RECAPS import recap3_1
recap3_1.get_details("Mark", "M", 26)
recap3_1.get_schooling(30000,260,900)
fw = open("Details.txt", "w")
fw.write(recap3_1.get_details("Mark", "M", 26))
fw.close()
I then get this error
Mark Male 26
Traceback (most recent call last):
29360
File "E:/PyProjects/YoutubeProject/RECAPS/recap3.py", line 8, in <module>
fw.write(recap3_1.get_details("Mark", "M", 26))
Mark Male 26
TypeError: write() argument must be str, not None
Process finished with exit code 1
the get_details function is just this,
def get_details(name, gender, age=0):
if age < 18:
print("You are too young to register")
return
if len(name) < 2:
print("Looks like your name is too short")
return
if gender is "M":
gender = "Male"
elif gender is "F":
gender = "Female"
else:
gender = "Unknown"
print(name, gender, age)
What am I missing. I was hoping to grab the function from another .py file and save the contents
Upvotes: 0
Views: 1510
Reputation: 31925
Based on your post, I can see get_details
do print output on console but it can't tell whether it returns anything or not.
def get_details(name, gender, age):
info = "{0} {1} {2}".format(name, gender, age)
print(info) # print on console
return info # you have to return a String
Python Input and Output:
f.write(string) writes the contents of string to the file, returning the number of characters written.
>>> f.write('This is a test\n')
>>> 15
Upvotes: 1
Reputation: 175
The method you are calling: recap3_1.get_details
is returning None
, not the value you want to write to file. Just because the values print to the screen does not mean that you are returning these strings when calling the function. Try:
test_var = recap3_1.get_details("Mark", "M", 26)
print(test_var)
You should see None
print to the screen. If you want the get_details
method to return a value to write to file, you have to specify in the method definition.
EDIT: Now that you've posted your code, you need your method to return a string... if you want the values space separated like your printed output, just do:
return ' '.join((name, gender, age))
instead of the print statement in get_details
, and your script should work as expected
Upvotes: 0
Reputation: 5542
It looks like the functions recap3_1.get_details
and recap3_1.get_schooling
print to stdout
directly instead of returning strings, that's why you're getting a None
instead of a string. In order to write their result, you need to get their output as a string. Can you modify their code?
Upvotes: 0