正在 Python 中打开 xlxs 工作簿,自动处理文件名

Opening xlxs workbook in Python, automating file name

我是 R 的重度用户,但对 Python 还是个新手。我正在尝试编辑属于更大工作流程一部分的 Python 脚本。该脚本首先打开一个 .xlsx 文档。此文档是在工作流的较早部分生成的,命名约定始终为 YYYYMMDD_location(例如:20191101_Potomac)。我想设置 Python 脚本,以便它自动将今天的日期和该位置变量粘贴到路径中。

在 R 中,为了不必每次 运行 脚本时都手动更新路径名,我会做类似的事情:

#R

library(openxlsx)

dir_name <- 'C:/path/to/file/'
location_selection <- 'Potomac'
date <- (paste(format(Sys.Date(),"%Y%m%d"))

open.xlsx(paste0(dir_name, date, "_", location_selection, ".xlsx")

我在 Python(例如:Build the full path filename in Python)中查看了如何设置类似的东西,但在制作有用的东西方面没有取得太大进展。

# Python

import datetime

dir_name = 'C:\path\to\file'
location_selection = todays_date.strftime('%Y%m%d')+'_Potomac'
suffix = '.xlsx'
file = os.path.join(dir_name, location_selection + suffix)

book = xlrd.open_workbook(file)


无需使用 os 模块,因为您提供了完整的目录路径。

from datetime import date

dir_name = r'C:\path\to\file'
location_selection = f"{date.today().strftime('%Y%m%d')}_Potomac"
suffix = '.xlsx'

file_name = f'{dir_name}\{location_selection}{suffix}'

book = xlrd.open_workbook(file_name)

我们还可以添加更多变量:

from datetime import date

dir_name = r'C:\path\to\file'
today = date.today().strftime('%Y%m%d')
location = "Potomac"
suffix = '.xlsx'

file_name = f'{dir_name}\{today}_{location}{suffix}'

book = xlrd.open_workbook(file_name)

最后我们可以创建一个可以重复使用的函数:

from datetime import date

def get_filename(location, dir_name=r'C:\path\to\file', suffix=".xlsx", date_format = '%Y%m%d'):
    today = date.today().strftime(date_format)
    return f'{dir_name}\{today}_{location}{suffix}'

book = xlrd.open_workbook(get_filename("Potomac"))
book2 = xlrd.open_workbook(get_filename("Montreal"))
book3 = xlrd.open_workbook(get_filename("NewYork"))