我有一個包含數百個檔案的檔案夾,名稱如下:
"2017_05_S2B_7VEG_20170528_0_L2A_B01.tif"
會議內容:
year_month_ID_zone_date_0_L2A_B01.tif ("_0_L2A_B01.tif"和"zone"永不改變)
我需要的是遍歷每個檔案并根據它們的名稱構建一個路徑以便下載它們。例如:
name = "2017_05_S2B_7VEG_20170528_0_L2A_B01.tif"
path = "2017/5/S2B_7VEG_20170528_0_L2A/B01.tif"
路徑約定需要是: path = year/month/year_month_ID_zone_date_0_L2A/B08.tif
我想制作一個回圈,每次遇到一個"_"字符時,它都會將我的字串“切割”成幾個部分,然后按正確的順序縫合不同的部分以創建我的路徑名。我試過這個,但沒有用:
import re
filename =
"2017_05_S2B_7VEG_20170528_0_L2A_B01.tif"
try:
found = re.search('_(. ?)_', filename).group(1)
except AttributeError:
# _ not found in the original string
found = '' # apply your error handling
我怎么能在 Python 上實作呢?
uj5u.com熱心網友回復:
由于您只有一個分隔符,您也可以簡單地使用 Python 的內置 split 函式:
import os
items = filename.split('_')
year, month = items[:2]
new_filename = '_'.join(items[2:])
path = os.path.join(year, month, new_filename)
uj5u.com熱心網友回復:
不需要正則運算式——你可以只使用split().
filename = "2017_05_S2B_7VEG_20170528_0_L2A_B01.tif"
parts = filename.split("_")
year = parts[0]
month = parts[1]
uj5u.com熱心網友回復:
試試下面的代碼片段
filename = "2017_05_S2B_7VEG_20170528_0_L2A_B01.tif"
found = re.sub('(\d )_(\d )_(.*)_(.*)\.tif', r'\1/\2/\3/\4.tif', filename)
print(found) # prints 2017/05/S2B_7VEG_20170528_0_L2A/B01.tif
uj5u.com熱心網友回復:
filename = "2017_05_S2B_7VEG_20170528_0_L2A_B01.tif"
temp = filename.split('_')
result = "/".join(temp)
print(result)
結果是
2017/05/S2B/7VEG/20170528/0/L2A/B01.tif
uj5u.com熱心網友回復:
也許你可以這樣做:
from os import listdir, mkdir from os.path import isfile, join, isdir
my_path = 'your_soure_dir'
files_name = [f for f in listdir(my_path) if isfile(join(my_path, f))]
def create_dir(files_name): for file in files_name: month = file.split(' ', '1')[0] week = file.split(' ', '2')[1] 如果不是 isdir(my_path): mkdir(month) mkdir(week) ### 你的下載代碼
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/336403.html
