Python Forum

Full Version: Traceback error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This runs, as in it appends the file. The problem is I get this traceback error and I don't know why.

employee_file = open("Employees.txt", "a")

employee_file.write("\nToby - Human resources")
employee_file.write("\nKelly - Customer service")

print(Employees.txt)

employee_file.close()
Error:
C:\Python365\python.exe F:/USERS/Tonya/Python/Draft/Writing_and_Appending_to_Files.py Traceback (most recent call last): File "F:/USERS/Tonya/Python/Draft/Writing_and_Appending_to_Files.py", line 8, in <module> print(Employees.txt) NameError: name 'Employees' is not defined Process finished with exit code 1
As always - thank you!
As it is, looks like you are trying to print the 'txt' attribute of Employees class.

Or you want to print the content of the file?

Write into the file:
with open("Employees.txt"), 'a') as employee_file:
    employee_file.write("\nToby - Human resources")
    employee_file.write("\nKelly - Customer service")
Read and print the content:
with open("Employees.txt"), 'r') as employee_file: # open for reading
    data = employee_file.read()

print(data)
Ok - I'm trying to append the records to the file and it works with the code I provided. It just had the traceback error. As it turns out - I shouldn't have had the print command where it was. It worked perfectly after that.

I tried the code your way as well. It also worked perfectly! Thank you!

How do you know which style to use?

Thanks again!
Using the with statement will close the file properly for you after its code block run so you don't have to remember to do that or can't forget it.