簡體   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