从csv输出python中删除所有逗号分隔符

时间:2014-01-24 01:38:00

标签: python csv tkinter

我在为tkinter应用程序生成输出时遇到一些麻烦,我想用它来允许用户输入地址并将它们附加到现有的csv上。 file我目前在导出期间出现的问题是地址中的每个字符都被分隔,因此代替31A Kabul st,它将是,3,1,A,K,a,b,u,l,s, t ...我知道我以前遇到过这个问题,它可能是一个简单的修复,但我是tkinter的新手,而且是python的新手。任何建议将不胜感激。科迪

from Tkinter import *
from tkFileDialog import *
import csv

"""GUI APPLICATION with Buttons"""
class Application(Frame):

    def __init__(self, master):
        """Initialise the frame"""
        Frame.__init__(self,master)
        self.grid()
        self.create_Main()
        self.location_columns()
        self.Column_box()
        self.loader_button()


    def create_Main(self):
        """Create 3 buttons that do nothing"""        
        self.button = Button(self, text="QUIT", fg="red", command=self.quit )
        self.button.grid(row =1, column= 6,sticky = E)   

        self.label0 = Label(self, text= "Enter address")
        self.label0.grid(row =1, column= 0, columnspan = 2, sticky = W)


    def location_columns(self):
        """Location Columns"""
        self.label = Label(self, text= "Flat letter or number")
        self.label.grid(row =2, column= 0, sticky = W)        

        self.label1 = Label(self, text= "Street Number")
        self.label1.grid(row =2, column= 1, sticky = W)

        self.label2 = Label(self, text= "Street Name")
        self.label2.grid(row =2, column= 2, sticky = W)

        self.label3 = Label(self, text= "St suffix")
        self.label3.grid(row =2, column= 3, sticky = W)

        self.label4 = Label(self, text= "Suburb or Town")
        self.label4.grid(row =2, column= 4, sticky = W)      

        self.label5 = Label(self, text= "City")
        self.label5.grid(row =2, column= 5, sticky = W)    

        self.label6 = Label(self, text= "Region")
        self.label6.grid(row =2, column= 6, sticky = W)                   

    def Column_box(self):
        """Column Assoc Textboxes"""
        self.textbox = Entry(self)
        self.textbox.grid(row = 3, column = 0, sticky = W)

        self.textbox1 = Entry(self)
        self.textbox1.grid(row = 3, column = 1, sticky = W)

        self.textbox2 = Entry(self)
        self.textbox2.grid(row = 3, column = 2, sticky = W)

        self.textbox3 = Entry(self)
        self.textbox3.grid(row = 3, column = 3, sticky = W)

        self.textbox4 = Entry(self)
        self.textbox4.grid(row = 3, column = 4, sticky = W)

        self.textbox5 = Entry(self)
        self.textbox5.grid(row = 3, column = 5, sticky = W)        

        self.textbox6 = Entry(self)
        self.textbox6.grid(row = 3, column = 6, sticky = W)     

        self.txt = Text(self, height=4, wrap = NONE)
        self.txt.grid(row=5, columnspan=7, sticky="nsew")
        self.txt.delete(0.0, END)
        self.txt.configure( state="disabled")        

        self.submit_button = Button(self, text = "Add to current", command = self.reveal)
        self.submit_button.grid(row = 4, column = 0, sticky = W) 

        self.flush_button = Button(self, text = "Add To File", command = self.Address)
        self.flush_button.grid(row = 10, column = 0, sticky = W)         

        """Scroll Bar"""        
        scrollb = Scrollbar(self.txt, command=self.txt.yview)
        scrollb.pack( side = RIGHT, fill=Y)
        self.txt['yscrollcommand'] = scrollb.set        

    def reveal(self):
        """prevents user from entering/editing the txt box and wrong format"""
        self.txt.configure(state="normal")

        content = self.textbox.get()
        content1 = self.textbox1.get()
        content2 = self.textbox2.get()
        content3 = self.textbox3.get()
        content4 = self.textbox4.get()
        content5 = self.textbox5.get()
        content6 = self.textbox6.get()        

        content = str(content.replace(" ",""))
        content1 = str(content1.replace(" ", ""))
        """content2 = str(content2.replace(" ", ""))
        #dont want to remove the space from roads like 
        # West Coast Road. etc..."""
        content3 = str(content3.replace(" ", ""))
        content4 = str(content4.replace(" ", ""))
        content5 = str(content5.replace(" ", ""))
        content6 = str(content6.replace(" ", ""))

        """Concatenate Flat and address fields"""
        try:
            content = int(content)
            AddNum = str(content) +"/" +str(content1)
        except ValueError:
            AddNum = str(content1) + str.upper(content)

        """Add all values onto string"""
        try:
            count = len(AddNum) +len(content2) + len(content3) +len(content4) +len(content5) +len(content6)
            if count == 0:
                self.errorbox = Label(self, fg="red",  text= "Please Enter an Address!")
                self.errorbox.grid(row =1, column= 1, columnspan = 2, sticky = W)
                raise Exception 
            else:
                try:
                    self.errorbox.destroy()
                    message = "'"+ str(AddNum)+"'", "'"+ str(content2) +"'","'"+ str(content3)+"'" , "'"+str(content4) +"'", "'"+str(content5)+"'" , "'"+str(content6)+"'"
                except:
                    message = "'"+ str(AddNum)+"'", "'"+ str(content2) +"'","'"+ str(content3)+"'" , "'"+str(content4) +"'", "'"+str(content5)+"'" , "'"+str(content6)+"'"

        except ValueError:
            try:
                self.errorbox.destroy()
            except:
                raise Exception 

        try: 
            content1 = int(content1)
        except ValueError:
            self.errorbox = Label(self,fg="red", text= "Street Number must be an integer!")
            self.errorbox.grid(row =1, column= 1, columnspan = 2, sticky = W)
            raise Exception 

        """Prevent interaction with txt box"""
        self.txt.insert(0.0 ,'\n')
        self.txt.insert(0.0 ,message)
        self.txt.grid(row=5, columnspan = 7, sticky="nsew")
        self.txt.configure( state="disabled")

    def loader_button(self):
        self.b_loader = Button(self, text = "Load File", command = self.loader)
        self.b_loader.grid(row = 9, column = 0, sticky = W)        

    def loader(self):
        self.filename = askopenfilename(parent=root)
        self.textbox10 = Entry(self, width = 60)
        self.textbox10.grid(row = 9, column = 1, columnspan = 3, sticky = W)        
        self.textbox10.insert(0,self.filename)  

        with open(self.filename, "r") as infile:
                Address = infile.read()
                self.contbox = Text(self, height=4, wrap = NONE)
                self.contbox.grid(row=11, columnspan=7, sticky="nsew")
                self.contbox.insert(0.0 ,Address) 
                self.contbox.configure( state="disabled")                    

                scrolla = Scrollbar(self.contbox,  command = self.contbox.yview)
                scrolla.pack( side = RIGHT, fill=Y)
                self.contbox['yscrollcommand'] = scrolla.set 

    def Address(self):
            Address = self.txt.get(0.0, END)
            list1= (Address)
            print list1
            if len(Address) <= 1:
                raise Exception
            else:
                with open(self.filename, 'a') as csvfile:
                    listwriter = csv.writer(csvfile, delimiter=',')
                    print Address
                    listwriter.writerow(Address)                    
            csvfile.close()

root = Tk()
root.title("AddressApp")
root.geometry("870x300")

app = Application(root)

root.mainloop()
root.destroy()

1 个答案:

答案 0 :(得分:2)

  

我目前在导出期间的问题是地址中的每个字符都被分隔,因此代替31A Kabul st,它将是,3,1,A,K,a,b,u,l ,,, S,T ...

这几乎总意味着你将一个字符串而不是一个字符串列表传递给writerow。请记住,字符串就像一个单字符串的序列。

所以最有可能的是,你想要改变的是:

listwriter.writerow([Address])                    

但是,如果您只有一个列,我不确定您为什么首先使用CSV。

更有可能的是,你真正想做的是首先让Address成为一个列表。您在代码中执行此类操作的所有位置:

message = "'"+ str(AddNum)+"'", "'"+ str(content2) +"'","'"+ str(content3)+"'" , "'"+str(content4) +"'", "'"+str(content5)+"'" , "'"+str(content6)+"'"

......你可能真的只是想要这个:

message = [AddNum, content2, content3, content4, content5, content6]

...至少如果message是您最终要尝试写入CSV的行。