英文:
Stop python loop (List)
问题
我是Python新手。我有一个循环:
# todaystr给出系统日期的字符串,例如202307
if not os.path.exists(os.path.join(folder, todaystr)):
os.makedirs(os.path.join(folder, todaystr))
for f in os.listdir(folder):
if not (f.startswith(todaystr) and f.endswith(".hl7")):
break
for g in os.listdir(folder)[:4]:
if g.endswith('.hl7') and g.startswith(todaystr):
shutil.move(os.path.join(folder, g), destination)
数据列表:
'202307',
'20230713-0955.hl7',
'20230713-0955.hl7',
'20230713-0955.hl7',
'20230713-0955.hl7',
'20230713-0955.hl7',
'202307XY'
循环应该在列表不再包含以"202307"开头且以"hl7"结尾的数据时停止。问题是有一个名为"202307"的文件夹,所以它立即停止。
谢谢
对不起我的英语不好。
我确定我的if子句内部有问题。
英文:
Im new to python. I have a loop
#todaystr gives string of sysdate e.g. 202307
if not os.path.exists(os.path.join(folder, todaystr )):
os.makedirs(os.path.join(folder, todaystr ))
for f in os.listdir(folder):
if not ( f.startswith(todaystr) and f.endswith("hl7")) :
break
for g in os.listdir(folder)[:4] :
if g.endswith('.hl7') and g.startswith (todaystr) :
shutil.move(os.path.join(folder, g),destination)
list data:
'202307',
'20230713-0955.hl7',
'20230713-0955.hl7',
'20230713-0955.hl7',
'20230713-0955.hl7',
'20230713-0955.hl7',
'202307XY'
The loop should stop as soon as the list contains no data starting with "202307" and ending with "hl7". The Problem is that there is a folder "202307" so he stops instantly.
Thank you
Sorry for my bad english.
Im sure i have a Problem inside my if clause
答案1
得分: 1
看起来你想要类似这样的东西:
import os
folder = "/path/to/folder"
for f in os.listdir(folder):
print(f)
if not (f.startswith("202307") and f.endswith("hl7")):
break
英文:
It sounds like you want something like this:
import os
folder = "/path/to/folder"
for f in os.listdir(folder):
print(f)
if not (f.startswith("202307") and f.endswith("hl7")):
break
答案2
得分: 0
你可以使用glob函数来获取与模式匹配的所有文件,然后确定是否存在一个值。
它可以从glob
模块导入,或者使用pathlib.Path
类的glob
方法。
import os
folder = "/path/to/folder"
print(glob.glob("202307*hl7", root_dir=folder))
"""
import pathlib
print(list(pathlib.Path(folder).glob("202307*hl7")))
"""
英文:
You can use the glob function to get all the files that match the pattern, and then determine whether there is a value.
It can be imported from the glob
module, or using the glob
method of the pathlib.Path
class.
import os
folder = "/path/to/folder"
print(glob.glob("202307*hl7", root_dir=folder))
"""
import pathlib
print(list(pathlib.Path(folder).glob("202307*hl7")))
"""
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论