如何插入新列并将其导出到Python中的CSV?

发布于 2025-01-23 04:08:17 字数 2744 浏览 2 评论 0原文

我有一个按钮将数据从MySQL导出到CSV文件中。获取的数据可能具有单行或多行。我想在每行数据的左列上添加一个新列,称为项目NO(标头),并且根据行数增加了值。如果有3行,则第一行将被标记为1,然后将其标记为2和3。我的代码执行SQL查询以获取数据并将其填充在列表中。然后将值传递到另一个函数以生成和导出CSV文件。谁能建议执行此操作的最佳方法?谢谢。

当前输出: 所需的输出:

def Company_Excel(asset_Box, ID_Box, newid_Entry, temp_Entry, gps_Entry, current_Entry, PID_Box, projectid_Entry, projectname_Entry, projectpic_Entry, piccontact_Entry, plocation_Entry, name_Entry, company_Entry, email_Entry, contact_Entry, issue_Entry, return_Entry, status_Entry, remarks_Entry, tree, company_Box):

    try:  
        company = company_Box.get()  
        if (company_Box.get() != "Please select one"):
            
            ncommand = ("SELECT `ID`, `Type`, `Project`, `Name`, `Location` from `History` WHERE `Company` = %s ORDER BY `Transaction ID`")
            mycursor.execute(ncommand,(company_Box.get(),))
            nresult = mycursor.fetchall()

            array6 = []
            for e in range(len(nresult)):
                nresult[e] = list(nresult[e])
                array6.append(nresult[e])
                
            write_to_csv_company(array6)
            
            if os.path.exists("Company.csv"):
              os.remove("Company.csv")
            else:
              print("The file does not exist")
              
            tkinter.messagebox.showinfo("Exported", "Success!")

        elif (company_Box.get() == "Please select one"):
            valueErrorMessage = "Please select one from the drop down menu"
            tkinter.messagebox.showerror("Error", valueErrorMessage)
            
        else:
            valueErrorMessage = "Not found, please try again"
            tkinter.messagebox.showerror("Error", valueErrorMessage)
        
    except PermissionError:
            valueErrorMessage = "Please close all the excel files before exporting"
            tkinter.messagebox.showerror("Error", valueErrorMessage)
            
def write_to_csv_company(result):

    with open('Company.csv', 'w+', newline='') as f:
        w = csv.writer(f, dialect='excel')
        for record in result:
            w.writerow(record)
            
    with open('Company.csv',newline='') as f:
        r = csv.reader(f)
        data = [line for line in r]
    
    with open('Items by Company.csv','w',newline='') as f:
        w = csv.writer(f)
        w.writerow(['ID', 'Type', 'Project', 'Name', 'Location'])
        w.writerows(data) 

I have a button that exports data from MySQL into a CSV file. The fetched data may have single or multiple rows. I would like to add a new Column on the left most column called Item No(Header) for each row of data, and it's value increases based on the number of rows. If there are 3 rows, then the first row would be labelled as 1 and subsequently 2 and 3. My code performs a SQL query to fetch the data and populate it in a list. Then pass the values to another function to generate and export the CSV file. Could anyone suggest the best way to perform this? Thank you.

Current Output:
current output
Desired Output:
desired output

def Company_Excel(asset_Box, ID_Box, newid_Entry, temp_Entry, gps_Entry, current_Entry, PID_Box, projectid_Entry, projectname_Entry, projectpic_Entry, piccontact_Entry, plocation_Entry, name_Entry, company_Entry, email_Entry, contact_Entry, issue_Entry, return_Entry, status_Entry, remarks_Entry, tree, company_Box):

    try:  
        company = company_Box.get()  
        if (company_Box.get() != "Please select one"):
            
            ncommand = ("SELECT `ID`, `Type`, `Project`, `Name`, `Location` from `History` WHERE `Company` = %s ORDER BY `Transaction ID`")
            mycursor.execute(ncommand,(company_Box.get(),))
            nresult = mycursor.fetchall()

            array6 = []
            for e in range(len(nresult)):
                nresult[e] = list(nresult[e])
                array6.append(nresult[e])
                
            write_to_csv_company(array6)
            
            if os.path.exists("Company.csv"):
              os.remove("Company.csv")
            else:
              print("The file does not exist")
              
            tkinter.messagebox.showinfo("Exported", "Success!")

        elif (company_Box.get() == "Please select one"):
            valueErrorMessage = "Please select one from the drop down menu"
            tkinter.messagebox.showerror("Error", valueErrorMessage)
            
        else:
            valueErrorMessage = "Not found, please try again"
            tkinter.messagebox.showerror("Error", valueErrorMessage)
        
    except PermissionError:
            valueErrorMessage = "Please close all the excel files before exporting"
            tkinter.messagebox.showerror("Error", valueErrorMessage)
            
def write_to_csv_company(result):

    with open('Company.csv', 'w+', newline='') as f:
        w = csv.writer(f, dialect='excel')
        for record in result:
            w.writerow(record)
            
    with open('Company.csv',newline='') as f:
        r = csv.reader(f)
        data = [line for line in r]
    
    with open('Items by Company.csv','w',newline='') as f:
        w = csv.writer(f)
        w.writerow(['ID', 'Type', 'Project', 'Name', 'Location'])
        w.writerows(data) 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

半城柳色半声笛 2025-01-30 04:08:17

不确定最好的方法。但是我建议您这样做:

...
array6 = []
for e in range(len(result)):
    array6.append([e+1] + list(nresult[e]))
...
w.writerow(['Item NO', 'ID', 'Type', 'Project', 'Name', 'Location'])
...

Not sure about the best way. But I suggest you can do it like this:

...
array6 = []
for e in range(len(result)):
    array6.append([e+1] + list(nresult[e]))
...
w.writerow(['Item NO', 'ID', 'Type', 'Project', 'Name', 'Location'])
...
安稳善良 2025-01-30 04:08:17
import pandas as pd
df=pd.read_csv(yourfile,delimiter="delimiterthatyouhave")
df.insert(0, "Item no", [1,2])
df.to_csv(yourpath, index=False)

您也可以根据DF的长度生成列表。

import pandas as pd
df=pd.read_csv(yourfile,delimiter="delimiterthatyouhave")
df.insert(0, "Item no", [1,2])
df.to_csv(yourpath, index=False)

You can generate list based on length of df also.

芯好空 2025-01-30 04:08:17

您应该远离键盘,并考虑要做什么。您在数据库中有一些数据,并有一次将其返回一行的工具。您需要将其导出在CSV文件(带有标题行)中,并添加一个行号作为第一个字段。

只需一次通过:

try:  
    company = company_Box.get()  
    if (company_Box.get() != "Please select one"):
        
        ncommand = ("SELECT `ID`, `Type`, `Project`, `Name`, `Location` from `History` WHERE `Company` = %s ORDER BY `Transaction ID`")
        mycursor.execute(ncommand,(company_Box.get(),))

        with open('Items by Company.csv','w',newline='') as f:
            w = csv.writer(f)
            w.writerow(['Item NO', 'ID', 'Type', 'Project', 'Name', 'Location'])

            for i, row in enumerate(mycursor, 1):
                w.writerow([i] + list(row))
          
        tkinter.messagebox.showinfo("Exported", "Success!")

    elif (company_Box.get() == "Please select one"):
        valueErrorMessage = "Please select one from the drop down menu"
        tkinter.messagebox.showerror("Error", valueErrorMessage)
        
    else:
        valueErrorMessage = "Not found, please try again"
        tkinter.messagebox.showerror("Error", valueErrorMessage)
    
except PermissionError:
        valueErrorMessage = "Please close all the excel files before exporting"
        tkinter.messagebox.showerror("Error", valueErrorMessage)
        

You should keep away from your keyboard and think about what you are trying to do. You have some data in a database, and have tools that return it one row at a time. You want to export it in a csv file (with the heading row) and add a row number as the first field.

Just do that in one single pass:

try:  
    company = company_Box.get()  
    if (company_Box.get() != "Please select one"):
        
        ncommand = ("SELECT `ID`, `Type`, `Project`, `Name`, `Location` from `History` WHERE `Company` = %s ORDER BY `Transaction ID`")
        mycursor.execute(ncommand,(company_Box.get(),))

        with open('Items by Company.csv','w',newline='') as f:
            w = csv.writer(f)
            w.writerow(['Item NO', 'ID', 'Type', 'Project', 'Name', 'Location'])

            for i, row in enumerate(mycursor, 1):
                w.writerow([i] + list(row))
          
        tkinter.messagebox.showinfo("Exported", "Success!")

    elif (company_Box.get() == "Please select one"):
        valueErrorMessage = "Please select one from the drop down menu"
        tkinter.messagebox.showerror("Error", valueErrorMessage)
        
    else:
        valueErrorMessage = "Not found, please try again"
        tkinter.messagebox.showerror("Error", valueErrorMessage)
    
except PermissionError:
        valueErrorMessage = "Please close all the excel files before exporting"
        tkinter.messagebox.showerror("Error", valueErrorMessage)
        
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文