繁体   English   中英

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

[英]How would I tell Python to write to a new line if the previous line is occupied with other text?

假设我在通过Python脚本创建的文本文件的第一行上有文本。 我退出了脚本,几天后访问了它。 我要添加另一条信息,但是它将覆盖第一行。 我如何告诉Python在添加第x行之前对其进行检查? 我的代码在下面,您无需添加到我的代码中,只需给我一个简单的示例即可。 谢谢,

诺亚·雷尼(Noah Rainey)

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

您需要以“附加”模式打开文件,如下所示:

with open("filename", "a") as f:
     f.write("Next line\n")

open()调用中使用模式"w"将覆盖您的文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM