0

So I'm a beginner in python and I was trying the append commands. It worked very well with strings but not with floats. I used this:

Num1 = float(input("Enter 1st num: "))
Num2 = float(input("Enter 2nd num: "))
Salary = num1 - num2
employee_file = open("employee_salary.txt", "a")
employee_file.write(salary)
employee_file.close()

I know I could just remove float() from input but that was just an example, my program in more complicated than that and I don't want to remove float(). Is there any command to append float to a text file? Please help me.

2

3 Answers 3

2

You have to convert the float to a string first.

employee_file.write(str(salary))

Also, you might want to append a newline, as File.write() does not do that automatically.

employee_file.write(str(salary) + '\n')

Further, do not open and close files explicitely. It is considered better practice to do that with python's with construct:

num2 = float(input("Enter 2nd num: "))
salary = num1 - num2
with open("employee_salary.txt", "a") as employee_file:
    employee_file.write(str(salary) + '\n')
# No close necessary, the end of the with-paragraph closes the file automatically
Sign up to request clarification or add additional context in comments.

2 Comments

That's not off-topic, but a good advice, I would remove the words in bold if I were you
Sure, if you think that's better.
0

You could convert it to a string and then append, use str(x) for that.

Num2 = float(input("Enter 2nd num: "))
Salary = num1 - num2
employee_file = open("employee_salary.txt", "a")
employee_file.write(str(salary))
employee_file.close()

Comments

0

You need to convert your float to text to be able to write it to text file. If you are using Python 3.6 or newer you might use so-called f-strings. Just replace

employee_file.write(salary)

in your code with

employee_file.write(f"{salary}\n")

then it would always append salary and newline to your file. If you want to know more about f-strings I suggested reading this article. As side note I want to alert you that operations on floats might result in outcome, which is not correct from mathematical point of view, if you wish to read more about it there is relevant documentation piece. Due to this you might end with values less than 1 cent, in surprising places, consider following example:

s = 0.1+0.1+0.1
print(s)

Output:

0.30000000000000004

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.