简体   繁体   中英

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

Let's suppose I had text on line one of a text file created via to a Python script. I exit out of the script and then access it a few days later. I go to add another entry of information but it overwrites line one. How would I tell Python to check line x before adding to it? My code is below, you don't need to add to my code you can just give me a quick and simple example. Thanks,

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

You need to open the file in "append" mode, like this:

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

Using the mode "w" in the open() call will overwrite your file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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