【发布时间】:2021-03-11 16:09:08
【问题描述】:
我正在使用 python 使用元素和子元素过程创建 xml 文件。 我的文件夹中有一个 zip 文件列表,如下所示:
Retirement_participant-plan_info_v1_getPlankeys_rev1_2021_03_09.zip
Retirement_participant-plan_info_resetcache_secretmanager_rev1_2021_03_09.zip
Retirement_participant-plan_info_v1_mypru_plankeys_rev1_2021_03_09.zip
Retirement_participant-plan_info_resetcache_param_value_rev1_2021_03_09.zip
Retirement_participant-plan_info_resetcache_param_v1_balances_rev1_2021_03_09.zip
我想拆分这些 zip 文件并获得如下名称:
Retirement_participant-plan_info_v1_getPlankeys
Retirement_participant-plan_info_resetcache_secretmanager
Retirement_participant-plan_info_v1_mypru_plankeys
Retirement_participant-plan_info_resetcache_param_value
Retirement_participant-plan_info_resetcache_param_v1_balances
PS:我想在从 zip 文件创建名称时删除 _rev1_2021_03_09.zip。
这是我的 Python 代码。它适用于Retirement_participant-plan_info_v1_getPlankeys_rev1_2021_03_09.zip,但如果我的 zip 文件名称太大,例如 Retirement_participant-plan_info_resetcache_param_v1_balances_rev1_2021_03_09.zip,它就不起作用了
Proxies = SubElement(proxy, 'Proxies')
path = "./"
for f in os.listdir(path):
if '.zip' in f:
Proxy = SubElement(Proxies, 'Proxy')
name = SubElement(Proxy, 'name')
fileName = SubElement(Proxy, 'fileName')
a = f.split('_')
name.text = '_'.join(a[:3])
fileName.text = str(f)
【问题讨论】:
-
您想从末尾剥离的位是否始终相同,即
_rev1_2021_03_09.zip?还是会有所不同,但始终遵循该模式,例如改天可能是_rev8_2021_03_11.zip? -
我认为问题出在倒数第二行:
name.text = '_'.join(a[:3])。目前,它只是从_拆分中获取前 3 个段。由于您的文件名在开始时有不同的长度,这有时会切断文件名的一部分。由于结尾 是一致的,您可以将3更改为-4,这会将所有内容保留到最后四个部分。
标签: python python-3.x xml python-2.7