如果前一行被其他文本占用,我如何告诉Python写入新行?

Noa*_*h R 0 python line new-operator

假设我在通过Python脚本创建的文本文件的第一行上有文本.我退出脚本,几天后再访问它.我去添加另一条信息,但它会覆盖第一行.在添加之前,我如何告诉Python检查第x行?我的代码如下,你不需要添加到我的代码中,你可以给我一个快速而简单的例子.谢谢,

诺亚雷尼

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?"))
    favcolor = raw_input("What is your favorite color?")

    fileObj = open("employees.txt","w")
    fileObj.write("Name:"+name+" ")
    fileObj.write("Age:"+age+" ")
    s = line.split()
    n = len(s)
    fileObj.write('''

''')
    fileObj.close()
    print "The following text has been saved:"
    print "Name:"+name
    print "Age:"+age
    print "Favorite Color"+favcolor
    start()
def look_up():
    fileObj = open("employees.txt","r")
    line = raw_input("What line would you like to look up:")
    line = fileObj.readline()
    print line
Run Code Online (Sandbox Code Playgroud)

Sve*_*ach 5

您需要以"追加"模式打开文件,如下所示:

with open("filename", "a") as f:
     f.write("Next line\n")
Run Code Online (Sandbox Code Playgroud)

使用模式"w"open()通话将覆盖您的文件.