如何插入新列并将其导出到Python中的CSV?
我有一个按钮将数据从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:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不确定最好的方法。但是我建议您这样做:
Not sure about the best way. But I suggest you can do it like this:
您也可以根据DF的长度生成列表。
You can generate list based on length of df also.
您应该远离键盘,并考虑要做什么。您在数据库中有一些数据,并有一次将其返回一行的工具。您需要将其导出在CSV文件(带有标题行)中,并添加一个行号作为第一个字段。
只需一次通过:
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: