簡體   English   中英

通過 Python 打開具有特定文件名和路徑的 excel

[英]Open excel with specific filename and path via Python

我在同一路徑中有一個 2 excel 文件。 對於第一個excel,我給用戶一個輸入。 當他們輸入年月日時,它會發生 20210830(示例)。 正如您在下面看到的,我合並了用戶的輸入和固定的“dh”和固定的“路徑”。 如果此路徑包含此文件夾名稱,文件將打開。

我的 r 實際問題是關於“第二個 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)

注意:正如我告訴過你的,在最后一個“_”之后,打開文件而不考慮它后面的數字。

預計 output:

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)

使用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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM