如何防止csv文件名成为python中的工作表名称?
我是 python 新手,非常感谢一些帮助。我使用 Jupyter Notebook 将 SSMS 查询导出到 pandas 数据框,然后将数据框导出到 csv。我需要每个月运行这个 python 脚本,所以我正在寻找以某种格式保存的每月 csv 文件,即 CSV 文件名 + 上个月名称和名称。例如:CSV 文件名 2022 年 2 月,Python 脚本于 2022 年 3 月运行。
问题是该 CSV 文件的工作表名称显示 CSV 文件名以及月份名称和年份,我希望工作表名称保留为“Sheet1” ”,并且在运行 python 脚本时不会每月更改,即当我在 2022 年 4 月运行脚本时,我不希望工作表名称成为 2022 年 3 月的 CSV 文件名,而是保留为“Sheet1”
这是我的代码:
import pyodbc
import pandas as pd
import openpyxl
from datetime import date
from dateutil.relativedelta import relativedelta
last_month = date.today() - relativedelta(months=1)
text_date = format(last_month, '%B %Y')
server = 'server_name'
database = 'database_name'
cnxn = pyodbc.connect('DRIVER= {SQL Server};\
SERVER=' + server + '; \
DATABASE=' + database + ';\
Trusted_Connection = yes;')
sql_query = pd.read_sql_query("""Select * from Table""", cnxn)
df = pd.DataFrame(sql_query)
df.to_csv(r'filepath \filename' + str(text_date) + '.csv', index = False)
请帮助我。谢谢。
I'm new to python and would really appreciate some assistance. I exported the SSMS query to pandas data frame using Jupyter Notebook and then exported the data frame to csv. I need to run this python script every month so I am looking for the monthly csv file to be saved in a certain format i.e. CSV file name + Previous Month Name & Year eg: CSV File Name February 2022 when the python script is run in March 2022.
The problem is the Sheet Name of that CSV file shows CSV File Name along with Month Name and Year and I would like the Sheet Name to remain as "Sheet1" and not change every month when the python script is run i.e. when I run the script in April 2022 I do not want the Sheet Name to become CSV File Name March 2022 and instead remain as "Sheet1"
Here's my code:
import pyodbc
import pandas as pd
import openpyxl
from datetime import date
from dateutil.relativedelta import relativedelta
last_month = date.today() - relativedelta(months=1)
text_date = format(last_month, '%B %Y')
server = 'server_name'
database = 'database_name'
cnxn = pyodbc.connect('DRIVER= {SQL Server};\
SERVER=' + server + '; \
DATABASE=' + database + ';\
Trusted_Connection = yes;')
sql_query = pd.read_sql_query("""Select * from Table""", cnxn)
df = pd.DataFrame(sql_query)
df.to_csv(r'filepath \filename' + str(text_date) + '.csv', index = False)
Kindly help me on this. Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不认为你可以使用 df.to_csv 的sheet_name选项,尝试使用 df.to_excel
df.to_excel(filename,sheet_name="sheet_name",index=False)
I don't think you can have sheet_name option with df.to_csv, try using df.to_excel
df.to_excel(filename, sheet_name="sheet_name", index=False)