通过Python打开具有特定文件名和路径的excel

比安科内拉

我在同一路径中有 2 个 excel 文件。对于第一个 excel,我为用户提供了一个输入。当他们输入年-月-日时,它发生了 20210830(示例)。正如你在下面看到的,我合并了用户的输入和固定的“dh”和固定的“路径”。如果此路径包含此文件夹名称,文件将打开。

真正的问题是关于“第二个 Excel”。我想要的是当用户输入第一个 excel 的日期时,它将通过将同一文件路径中的第二个 excel 的名称和该日期之前的一个工作日组合起来来搜索文件

#first_excel = dh20210830
#second_excel = Test_Value_Serie_After_20210827_123456
path = K:\Test\
suffix = dh
final = path + dh + date
data = pd.read_csv(final,sep=';',encoding='utf-8')
df = pd.DataFrame(data)
add_year = str(input("Year:"))
add_month = str(input("Month:"))
add_day = str(input("Day:"))
date = add_year + add_month + add_day
suffix_second = Test_Value_Serie_After_
final_second = suffix_second + """""one business day before the user enters""""" + _123456 (But this number can be variable. So don't rely on these numbers. If there are different numbers, it may be in that file.)

constant variables = Test_Value_Serie_After_
path = K:\Test\
variable things = date(users input) and _123456(this number can be any number)

注意:正如我告诉你的,在最后一个“_”之后,无论后面的数字如何,都打开文件。

预期输出:

suffix_second = Test_Value_Serie_After_
date_second = date - 1 business day (in this example 20210827)...2 day is weekend)
final_second = suffix_second + date_second + '_'(open the file regardless of the numbers after it)
It_is_Chris

pd.tseries.offsets.BusinessDay如果您有特定的假期等,请使用或使用自定义工作日。

add_year = str(input("Year:"))
add_month = str(input("Month:"))
add_day = str(input("Day:"))
date = add_year + add_month + add_day
# convert date to datetime then offset 1 business day
date_offset = pd.to_datetime(date) - pd.tseries.offsets.BusinessDay(1) 

print(date_offset)

Year: 2021
Month: 08
Day: 30
2021-08-27 00:00:00

然后您可以将日期转换回字符串

str_date_offset = str(date_offset.date()).replace('-', '') # -> '20210827'

用户glob匹配文件名的模式

import glob

file_name = glob.glob(f'{suffix_second}{str_date_offset}_*.csv')[0]
print(file_name)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

尝试打开具有可变文件名的文件时,c程序崩溃

有没有办法在打开具有相似文件名的Excel文件时自动运行宏?

打开具有特定扩展名的新文件时的默认文本(例如:.cpp)

打开具有特定扩展名的文件,无论名称如何

读取CSV,如果文本匹配,则打开具有匹配文件名的html文件,然后以文本形式复制

打开具有变量名的文件

打开具有特定名称模式的不同文件夹和工作表?

如何在Python2和3上打开具有已知编码的文件?

具有特定扩展名的文件名的文件路径

如何在C ++中打开具有相对路径的文件?

如何通过比较文件名仅打开特定的excel文件?

如何在VBA中打开具有特定名称的文件夹中的文件?

Apache:防止打开具有非pdf扩展名的PDF文件

打开具有特定相册/文件夹的默认“照片”应用

如何打开具有特定专辑或文件夹的默认图库应用程序?

在屏幕上打开具有特定大小和位置的Internet Explorer

如何使用C#打开具有写保护的Excel文件

通过Python win32com打开Excel文件,文件名中包含外语

Python在json文件中的字典中打开具有相同键名的新文件

创建href,以打开具有特定地址的Google地图

如何从没有扩展名的路径中获取特定文件名python

C#使用`[]`保存具有特定文件名的excel文件不起作用

如何打开具有可修改的文件

使用子目录列出指定路径中具有完整路径和大小的所有文件名

提取具有匹配文件名的全路径

如何在Python中从具有完整路径的变量中获取文件名?

如何使用python和dataframe从excel中的路径获取基本文件名

上载具有特定文件名的文件

防止Glob选择具有特定文件名的文件