help! simple question
the topic is writing/reading text files, but i got this simple question. how do i make this program so it will look like this: http://i39.tinypic.com/5554wi.jpg i can't figure it out.
- to make it keep looping and asking "enter your name or break to exit" continue the question until the user enters break.
try my program and be apreciated is neone can help me fill in the missing code. ty
# Anna Huang
# Programming Assignment 16
blank=""
while not blank:
y = open("pa16names.txt", "w")
x = raw_input("Enter your name or break to exit:")
y.writelines(x)
y. close()
y = open ("pa16names.txt", "r")
print "The names you've entered into the text file are:", y.read()
y.close()
StarZ
Junior Poster in Training
85 posts since Dec 2008
Reputation Points: 11
Solved Threads: 1
Two things:
1) Separate the code that goes into the loop from code that does not loop by using proper indentations
2) Unless this is an exercise in writelines(), it is better to build a temporary string with the names entered in the loop, and then write that temporary string to the file after your break out of the loop. Otherwise you have to worry about appending a file, and if the file exists to start with an empty file.
Here is your code corrected to work properly:
# Anna Huang
# Programming Assignment 16
# start with empty temp string
temp = ""
while True:
name = raw_input("Enter your name (just Enter to exit): ")
if name:
# build up the temp string and end the name with a space
temp += name + ' ' # same as: temp = temp + name + ' '
else:
break
#print temp
fw = open("pa16names.txt", "w")
# write the temp string to file
fw.write(temp)
fw.close()
fr = open ("pa16names.txt", "r")
print "The names you've entered into the text file are:", fr.read()
fr.close()
Please read the comments so you can learn something at least.
sneekula
Nearly a Posting Maven
2,427 posts since Oct 2006
Reputation Points: 961
Solved Threads: 212
hey thanks, but do you know how I can make it so when the user types 'break' it will exit instead of enter to exit
StarZ
Junior Poster in Training
85 posts since Dec 2008
Reputation Points: 11
Solved Threads: 1
It would be something like this ...
...
while True:
name = raw_input("Enter your name (or break to exit): ")
if name == 'break':
break
else:
# build up the temp string and end the name with a space
temp += name + ' ' # same as: temp = temp + name + ' '
...
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417