【问题标题】:How can I create a new excel file every time a Python script runs?每次运行 Python 脚本时,如何创建一个新的 excel 文件?
【发布时间】:2021-06-28 10:53:23
【问题描述】:

我有一个单一来源的 Excel 文件,我每个月都会使用 Python 清理它,以便只与我的团队共享选定的数据。我想每个月创建一个新的 excel 文件,而不是每个月更新同一个文件。

例如 - 我已运行 Python 脚本并为 6 月创建了一个干净的文件。当它在 7 月运行时,我希望创建一个新文件,而不是更新 6 月的文件。

希望这是有道理的。提前致谢!

import os.path

from datetime import datetime

curr_date = datetime.strftime(datetime.now(), '%B')

save_path = 'T:/1. 2021 Timesheets n Bandwidth Tracker/Project Database/RA Copy/'

name_of_file = "PRO Project DB_2021_RA_" + curr_date.upper()

completeName = os.path.join(save_path, name_of_file+".xlsx") 

file1 = open(completeName, "w")

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 欢迎来到 *,请使用 tour 并附上 minimal, reproducible example,说明您迄今为止所做的工作和面临的问题。
  • 您的数据是什么样的?如何从 Excel 文件中读取数据?

标签: python excel


【解决方案1】:

您能否分享将文件保存为 .xls 或 .xlsx 文件的代码行?

代码是否也读入旧的 excel 文件?

如果您打开 Python 脚本并对文件名执行 Ctrl+F,这可能会有所帮助。

最简单的解决方案是每月手动更改文件名。只需在保存它的代码部分的文件名末尾添加:“Jul21”(下个月“Aug21”等)。如果将旧文件加载到 Python 中,您还需要更改其中的文件名以匹配。

【讨论】:

  • 我已编辑问题以包含代码。基本上,代码计划每月运行一次,并使用当前月戳自动更新文件名。是的,手动方式可能是一种方式,但我只是想知道是否有一种自动化方式。
【解决方案2】:

我可能会为此推荐pandas,但您需要一个第三方库,例如xlsxwriteropenpyxl

如果您不想使用 pandas,下面是使用库 xlsxwriter 的简单示例,但这取决于您的数据格式。我也在使用pathlib,因为它使一些事情变得更容易。

import xlsxwriter
from pathlib import Path
from datetime import datetime as dt

# Create a folderpath Path object.
output_folder = Path(r"T:/1. 2021 Timesheets n Bandwidth Tracker/Project Database/RA Copy")

# Set your timestamp variables.
today = dt.today()
this_month = today.strftime("%B")   # June
this_year = today.year              # 2021


# Create output path for excel file with month and year added.
full_xl_path = output_folder.joinpath(f"PRO Project DB_{this_year}_RA_{this_month}.xlsx")

# Create workbook and worksheet from given variables.
workbook = xlsxwriter.Workbook(full_xl_path)
worksheet = workbook.add_worksheet(name="Sheet1")


# Data sample
columns = ["employee", "date", "hours"]
data = [
    ["john", "2021-06-26", 8],
    ["dan", "2021-06-26", 8],
    ["joanna", "2021-06-27", 8],    
    ]

# For each row
for r in range(0, len(data) + 1):
    # If this is the firs row.
    if r == 0:
        # Write column headers.
        for h in range(len(columns)):
            worksheet.write(r, c, columns[h])    
    else:
        # Reset r to zero for indexing the data set.
        adjusted_r = r - 1
        for c in range(len(data[adjusted_r])):
            worksheet.write(r, c, data[c])
            
# Close workbook once complete.
workbook.close()

【讨论】: