格式化输出格式不正确(Python)

时间:2011-01-24 17:33:18

标签: python format

当我使用下面的代码时,我的输出格式很差。其中一个主要输出问题是/ n。 / n没有显示在真实文本文件中,但是从Python脚本中查看它都是“未格式化”。

代码:

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()

阅读和印刷的结果是:

['\ n','姓名:Noah \ n','-------------------------- \ n','年龄:16 \ n','薪水:20000 \ n','州:NC \ n','-------------------------- \ n','\ n','\ n','姓名:Daniel Rainey \ n','-------------------------- \ n','年龄:18 \ n','工资:200000 \ n','州:NC \ n','---------------------- ---- \ n','\ n','\ n','姓名:fdadas \ n','----------------------- --- \ n','年龄:343 \ n','工资:344433 \ n','州:NC \ n','------------------ -------- \ n','\ n','\ n']

2 个答案:

答案 0 :(得分:3)

print line

您正在打印list,这就是打印元素的原因。

尝试迭代它然后打印:

for ele in line:
    print ele

答案 1 :(得分:1)

尝试使用.read()代替.readlines()

def look_up():
    fileObj = open("employees.txt")
    contents = fileObj.read()
    print contents
    start()

readlines()将列表文件的行read()作为单个字符串读取。