如何在 Python 中插入新列并将其导出为 CSV?
How to insert a new column and export it to CSV in Python?
我有一个按钮可以将数据从 MySQL 导出到 CSV 文件中。获取的数据可能有单行或多行。我想在最左边的列中为每行数据添加一个名为 Item No(Header) 的新列,它的值会根据行数增加。如果有 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)
不确定最佳方法。但我建议你可以这样做:
...
array6 = []
for e in range(len(result)):
array6.append([e+1] + list(nresult[e]))
...
w.writerow(['Item NO', 'ID', 'Type', 'Project', 'Name', 'Location'])
...
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 的长度生成列表。
你应该远离你的键盘,想想你想做什么。您在数据库中有一些数据,并且有工具可以一次 return 一行。您想要将其导出到 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)
我有一个按钮可以将数据从 MySQL 导出到 CSV 文件中。获取的数据可能有单行或多行。我想在最左边的列中为每行数据添加一个名为 Item No(Header) 的新列,它的值会根据行数增加。如果有 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)
不确定最佳方法。但我建议你可以这样做:
...
array6 = []
for e in range(len(result)):
array6.append([e+1] + list(nresult[e]))
...
w.writerow(['Item NO', 'ID', 'Type', 'Project', 'Name', 'Location'])
...
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 的长度生成列表。
你应该远离你的键盘,想想你想做什么。您在数据库中有一些数据,并且有工具可以一次 return 一行。您想要将其导出到 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)