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.
精彩评论