how about changing to append mode 'a' instead of 'w'
Also looks like you have same file open twice, line 26 and 28 for writing.
Finally you are not really using the csv module, but doing by hand at line 30.
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
Here example of adding with plain open and write (starting with your example list):
def print_cities(title):
print title.center(40,'*')
with open('cities.csv') as citylist:
print 'Cities:\n',citylist.read()
def add_city(city_info):
with open('cities.csv','a') as citylist:
citylist.write('%s, %i, %i\n' % city_info)
print_cities('Before')
new_city = ('Espoo', 123, 212)
add_city(new_city)
print_cities('After')
"""Output:
*****************Before*****************
Cities:
a,1,2
b,3,4
c,5,6
d,7,8
*****************After******************
Cities:
a,1,2
b,3,4
c,5,6
d,7,8
Espoo, 123, 212
"""
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
Note that this line will never be true because city_name is a string, i.e. "0" != 0.
if city_name==0:
Also you compare if xcoord==0: twice and don't check ycoord. You can combine all of the input into a loop and avoid the redundancy, and FYI you are writing to a text file so all fields will be stored as strings, i.e. there is no reason to input floats unless you want to check for valid input.
spamWriter = open('cities.csv', 'a') ## 'a' = append additional recs if file exists
total=input("How many cities do you have? ")
x = 0
while x < total:
print
output_list = []
for lit in ["What is the name of your city?<'0' exits> ", \
"What is the x coordinate?<'0' exits> ", \
"What is the y coordinate?<'0' exits> " ]:
response = raw_input(lit)
if response == '0':
break
else:
output_list.append(response)
x+=1
## write each record as it is entered
spamWriter.write("%s, %s, %s\n" % \
(output_list[0], output_list[1], output_list[2]))
raw_input("press enter to exit")
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714