0

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']

1
  • You should always close every opened file with .close(). If not, depending on the garbage collector ordering some really obscure bug will surface, like the file not getting updated. Commented Jan 24, 2011 at 17:41

2 Answers 2

3
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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

When I try this nothing is outputted.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.