Hi I am fairly new at pyhton and I am trying to create a program to append a new row of raw input to the bottom of my existing .csv file. So far I have this:

import csv
x=1
y=1
n=0
citiesx=[]
citiesy=[]
city_names=[]
total=input("How many cities do you have? ")
while x in range(0,total+1):
   city_name=raw_input("What is the name of your city?<'0' exits> ")
   if city_name==0:
      break
   else:
      xcoord=input("What is the x coordinate?<'0' exits> ")
   if xcoord==0:
      break
   else:
      ycoord=input("What is the y coordinate?<'0' exits> ")
   if xcoord==0:
      break
   else:
      city_names.append(city_name)
      citiesx.append(xcoord)
      citiesy.append(ycoord)
      x+=1
w = csv.writer(open('cities.csv','w'))

spamWriter = csv.writer(open('cities.csv', 'wb'), delimiter=' ',
                        quotechar=' ', quoting=csv.QUOTE_MINIMAL)
while y in range(0,total+1):
   spamWriter.writerow([city_names[n]] + [','] + [citiesx[n]] + [','] + [citiesy[n]])
   n+=1
   y+=1
   
raw_input("press enter to exit")

That creates the .csv file which would look similar to this(commas meaning new cell):
a,1,2
b,3,4
c,5,6
d,7,8

What the next program would need to do is add another row of inputed data from the user i.e. e,9,10. I feel like I have tried everything to make this work. If anybody has some code to append a new row or can help me out that would be great.

Thanks,


Jaro

Edited 5 Years Ago by jarograv: add details

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.

Edited 5 Years Ago by pyTony: n/a

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
"""

Edited 5 Years Ago by pyTony: functions

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")

Edited 5 Years Ago by woooee: n/a

The answer didnt work for me. I have python 3 so that may be why but i made a fixed version for python 3.

def print_cities(name):
    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')
This article has been dead for over six months. Start a new discussion instead.