我已经创建了一个Tkinter应用程序来存储CSV文件中的数据.代码如下:

def add_file():
    global msg
    msg = entry.get()
    print(msg)
    if msg != '':
        listbox_tasks.insert(END, msg)
        entry.delete(0, END)
    else:
        messagebox.showinfo('Info', 'Please Fill In The Entry Box!')

def save_file(msg):
    with open('hello.csv', 'a', newline='') as f:
        writer = csv.writer(f, quotechar='"', quoting=csv.QUOTE_ALL)
        writer.writerow([msg])
    messagebox.showinfo('Info', 'Message Saved!')

scrollbar_tasks = Scrollbar(root)
scrollbar_tasks.pack(side=RIGHT, fill=Y)

listbox_tasks = Listbox(root, yscrollcommand=scrollbar_tasks.set, height=12, width=32, 
                         font=('Helvatica', 18))
listbox_tasks.pack(pady=20)

entry = Entry(label_frame1, font=('Helvatica', 18))
entry.grid(row=0, column=1)

my_create = Button(label_frame2, text='Add File', 
                   font=('Helvatica', 15), command=add_file)
my_create.grid(row=0, column=0, pady=10, padx=10)

my_entry = Button(label_frame2,  text='Save File', bg='green', fg='#ffffff',
                   font=('Helvatica', 15), command=lambda:save_file(msg))
my_entry.grid(row=1, column=0, pady=10, padx=10)

当我输入1,Apple在条目中并点击保存文件按钮,在我的CSV文件中显示为"1,Apple"而不是1,"Apple".

我怎么才能把绳子拔出来呢?

推荐答案

此编写器函数用于拆分小数数据(不带引号)和其他数据(带引号).

这是编写器函数:

decimals = {'0','1','2','3','4','5','6','7','8','9','.'}
def save_file(msg):
    with open('hello.csv', 'a', newline='') as f:
        msg += ","#ending char
        formatted = ''
        quote = False
        block = ''
        for i in msg:
            if i not in decimals:
                if i != ",":
                    quote = True
                    block += i
                else:
                    if quote:
                        block = '"'+block+'"'
                    formatted += block
                    formatted += ','
                    #new block
                    quote = False
                    block = ''
            else:
                block += i
        formatted = formatted[:-1]#remove ending char
        f.write(formatted+"\n")

    messagebox.showinfo('Info', 'Message Saved!')

当我使用这个时:

msg = "2,gerry,2.2,erderrer,42.0,22hellohelloh4llo,123.456789"
save_file(msg)

我在CSV文件中看到了这一点:

2,"gerry",2.2,"erderrer",42.0."22helloh4llo",123.456789

该行以换行符结尾.

Python相关问答推荐

两极:滚动组,起始指数由不同列设置

从多行文本中提取事件对

每个组每第n行就有Pandas

具有多个组的条形图的不同y标度

删除pandas rame时间序列列中未更改的值

Plotly:如何更改Heatmap中彩色条的勾选文本

max_of_three使用First_select、second_select、

如何访问所有文件,例如环境变量

管道冻结和管道卸载

PMMLPipeline._ fit()需要2到3个位置参数,但给出了4个位置参数

当独立的网络调用不应该互相阻塞时,'

使用密钥字典重新配置嵌套字典密钥名

cv2.matchTemplate函数匹配失败

为一个组的每个子组绘制,

如何使Matplotlib标题以图形为中心,而图例框则以图形为中心

如何在Python中使用另一个数据框更改列值(列表)

基于形状而非距离的两个numpy数组相似性

AES—256—CBC加密在Python和PHP中返回不同的结果,HELPPP

Python Tkinter为特定样式调整所有ttkbootstrap或ttk Button填充的大小,适用于所有主题

以逻辑方式获取自己的pyproject.toml依赖项