Reputation: 5477
When I use the below code I get a very poorly formatted output. One of the main output problems are the /n. The /n don't show up in the real text file, but viewing it from the Python script it's all "unformatted".
The code:
def start():
command = raw_input('''
1) Add
2) Look Up
3) See All
4) Delete Entry
''')
if command=="1":
add()
if command=="2":
look_up()
def add():
name = raw_input("What is your name?")
age = str(raw_input("How old are you?"))
salary = raw_input("Enter Salary:")
state = raw_input("State:")
fileObj = open("employees.txt","a")
fileObj.write("Name:"+name+"\n")
fileObj.write('--------------------------\n')
fileObj.write("Age:"+age+"\n")
fileObj.write("Salary:"+salary+"\n")
fileObj.write("State:"+state+"\n")
fileObj.write("--------------------------\n")
fileObj.write("\n\n")
fileObj.close()
print "The following text has been saved:"
print "Name:"+name
print "Age:"+age
print "Salary:"+salary
print "State:"+state
print "Note: This text was assigned to one line."
start()
def look_up():
fileObj = open("employees.txt")
line = fileObj.readlines()
print line
start()
start()
The outcome of reading and printing is:
['\n', 'Name:Noah\n', '--------------------------\n', 'Age:16\n', 'Salary:20000\n', 'State:NC\n', '--------------------------\n', '\n', '\n', 'Name:Daniel Rainey\n', '--------------------------\n', 'Age:18\n', 'Salary:200000\n', 'State:NC\n', '--------------------------\n', '\n', '\n', 'Name:fdadas\n', '--------------------------\n', 'Age:343\n', 'Salary:344433\n', 'State:NC\n', '--------------------------\n', '\n', '\n']
Upvotes: 0
Views: 284
Reputation: 601411
Try .read()
instead of .readlines()
:
def look_up():
fileObj = open("employees.txt")
contents = fileObj.read()
print contents
start()
readlines()
reads a the lines of the file as a list, read()
as a single string.
Upvotes: 1
Reputation: 131577
print line
You are printing a list
and that is why the elements get printed.
Try iterating over it and then printing:
for ele in line:
print ele
Upvotes: 3