在Python中给变量添加.xlsx扩展名

0 投票
3 回答
64 浏览
提问于 2025-04-12 12:00

我有一些Python代码,它可以从PDF文件中提取数据,并把这些数据转换成Excel文件。接着,它会从这个Excel文件中抓取特定的数据,并把这些数据保存到一个新的Excel文件里。我想给最终的Excel文件起个独特的名字,所以我想用datetime.now().isoformat()这个方法来实现。于是我把datetime.now().isoformat()保存为一个字符串,然后想在这个字符串后面加上.xlsx的后缀,以便形成一个独特的名字。但是我就是搞不明白怎么把.xlsx加到这个变量后面。

from spire.pdf.common import \*
from spire.pdf import \*
import os
import openpyxl
from openpyxl import load_workbook
from datetime import datetime
import xlsxwriter
current_dateTime = datetime.now().isoformat()
**#This is where I create the variable with the .xlsx extension**
dt = str(current_dateTime) + ".xlsx"
pdf = PdfDocument()
pdf.LoadFromFile("c:/Documents/Projects/file.pdf")
pdf.SaveToFile("excel/template.xlsx", FileFormat.XLSX)
pdf.Close()
folder = 'excel'
**#This is where I try to create the output file with the .xlsx extension**
output_file = dt
output_wb = openpyxl.Workbook()
output_sheet = output_wb.active
output_sheet.title = 'Bearskin'
cells = \['BQ34', 'G13', 'J22'\]
for filename in os.listdir(folder):
    if filename.endswith('.xlsx'):
    file = os.path.join(folder, filename)
    workbook = openpyxl.load_workbook(file)
    values = \[workbook.active\[cell\].value for cell in cells\]
output_sheet.append(values)
output_sheet.insert_rows(1)
output_sheet\['A1'\]= "Section"
output_sheet\['B1'\]= "Operation"
output_sheet\['C1'\]= "Depth"
output_sheet\['D1'\]= "Duration"
output_sheet\['E1'\]= "Cumulative Hours"
output_sheet\['F1'\]= "Cumulative Days"
output_wb.save(output_file)

3 个回答

0

你可以用多种方式来拼接字符串,其中一种方法是:output_file = str(dt) + ".xlsx"

如果想要更高级的用法,可以使用内置的format%函数,它们的用法类似于C语言中的printf函数。

举个例子:

output_file = "{}.xlsx".format(dt))

补充说明:

你会收到一个OSError: [Errno 22] Invalid argument的错误,因为你的文件名包含了无效字符(从文件系统的角度来看)。如果你不一定要使用ISO时间格式的话,可以使用strftime函数来改变生成的时间字符串的表示方式。

dt = datetime.datetime.strftime(datetime.datetime.now(), "%Y%m%dT%H%M%S.%s")
output_file = "{}.xlsx".format(dt))

这样生成的文件名格式会是:20240404T102547.1712219147.xlsx

0

如果你想创建一个独特的文件名,可以试试使用Unix时间戳。

from datetime import datetime

outputfile = "{}.xlsx".format(str(datetime.utcnow().timestamp()).replace('.', ''))
0

问题出在把日期时间(datetime)引入进来,然后试图把它当作变量dt来使用。当我用下面的代码生成一个随机字符串时:

(''.join(random.choices(string.ascii_lowercase, k=12)))

这个方法就能正常工作。所以对于那些想要这样做的人,建议你生成一个随机字符串,而不是试图用日期时间来作为变量。

撰写回答