Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Traceback error
#1
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!
Reply
#2
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)
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
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!
Reply
#4
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.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Traceback error tjnichols 8 4,047 Sep-26-2018, 08:14 PM
Last Post: ThiefOfTime

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020