Python 关于文件名的条件语句
我在以下庄园中有一个名为dat文件的目录:Python 关于文件名的条件语句,python,string,if-statement,conditional-statements,Python,String,If Statement,Conditional Statements,我在以下庄园中有一个名为dat文件的目录: 4sl_shear11_scale0.dat, -8_shear1_scale5.dat, -18sl_shear0_scale2.dat, ... 我想添加一个基于文件名的条件语句,特别是shear\n。情况会是这样吗 if shear_n > 20: do the thing elif shear_n < 10: do the other thing else: do nothing 如果剪力>20: 做
4sl_shear11_scale0.dat,
-8_shear1_scale5.dat,
-18sl_shear0_scale2.dat,
...
我想添加一个基于文件名的条件语句,特别是shear\n
。情况会是这样吗
if shear_n > 20:
do the thing
elif shear_n < 10:
do the other thing
else:
do nothing
如果剪力>20:
做那件事
elif剪力<10:
做另一件事
其他:
无所事事
通常我会选择文件名的索引,但剪切数的索引会因-和sl而改变。
做这件事最可靠的方法是什么?根据文件名的格式,并假设您可以作为字符串访问它们,您可以依赖一些字符串操作的“算法” 比如:
filenames = [
'4sl_shear11_scale0.dat',
'-8_shear1_scale5.dat',
'-18sl_shear0_scale2.dat'
]
for f in filenames:
shear = f.split('_')[1] # split the filename and grab the second part
shear_n = ''.join(d for d in shear if d.isdigit()) # strip the letters
shear_n = int(shear_n) #convert it to an int
假设您的所有文件在下划线之前都有一个数字,我认为这样就可以了:
import re
filename = "-18sl_shear0_scale2.dat"
first_item = filename.split("_")[0]
shear_n = int(re.findall('\d+', first_item)[0])
print(shear_n)
# >>> 18
你的意思是
shearn
而不是shearn
@jarmod在你的评论之前我想他想要下划线之前的数字。我现在有点糊涂了。太好了,我忘了拆分。