用于删除具有特定扩展名的诊断文件的脚本
Script to remove diagnostic files with specific extension
我有时间相关的诊断输出文件,例如
output1.1
output1.2
output1.3
.
.
.
output1.998
output1.999
output1.1000
output2.1
output2.2
output2.3
.
.
.
output2.998
output2.999
output2.1000
如何删除大于某个时间步(例如 t=500)的所有文件?
我希望有多种方法可以做到这一点,所以我愿意接受多种建议。
shell 中的类似内容:
for file in output*.*; do
if [ "${file##*.}" -gt 500 ]; then
rm "$file"
fi
done
${variable##pattern}
从变量内容的开头删除 pattern 的最长匹配项。在这种情况下,它只为您提供文件名最后一个句点之后的数字。
调用 rm
次数较少的版本(如果有问题):
for file in output*.*; do
if [ "${file##*.}" -gt 500 ]; then
printf "%s[=11=]" "$file"
fi
done | xargs -0 rm
import os
os.chdir(path)
for file in os.listdir(path):
try:
if int(file.split(".")[1]) >= 500:
os.remove(file)
except (OSError, ValueError):
#couldnt remove the path, non time postfix path or os error
import os
files = [x for x in os.listdir() if int(x.split('.')[1]) > 500]
for file in files:
os.remove(file)
如果您的所有文件都在一个文件夹中,这将可行。将我的路径更改为您的路径。
from os import listdir, remove
from os.path import isfile, join
mypath = 'D:\Files\Python\Output'
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
for f in onlyfiles:
if int(f.split('.')[1]) > 500:
remove(mypath+'\'+f)
在 python 中您可以尝试以下操作:
from pathlib import Path
p = Path('.')
for name in p.glob('*.[0-9]*'):
ext = name.suffix
if int(ext) > 500:
name.unlink()
我有时间相关的诊断输出文件,例如
output1.1
output1.2
output1.3
.
.
.
output1.998
output1.999
output1.1000
output2.1
output2.2
output2.3
.
.
.
output2.998
output2.999
output2.1000
如何删除大于某个时间步(例如 t=500)的所有文件?
我希望有多种方法可以做到这一点,所以我愿意接受多种建议。
shell 中的类似内容:
for file in output*.*; do
if [ "${file##*.}" -gt 500 ]; then
rm "$file"
fi
done
${variable##pattern}
从变量内容的开头删除 pattern 的最长匹配项。在这种情况下,它只为您提供文件名最后一个句点之后的数字。
调用 rm
次数较少的版本(如果有问题):
for file in output*.*; do
if [ "${file##*.}" -gt 500 ]; then
printf "%s[=11=]" "$file"
fi
done | xargs -0 rm
import os
os.chdir(path)
for file in os.listdir(path):
try:
if int(file.split(".")[1]) >= 500:
os.remove(file)
except (OSError, ValueError):
#couldnt remove the path, non time postfix path or os error
import os
files = [x for x in os.listdir() if int(x.split('.')[1]) > 500]
for file in files:
os.remove(file)
如果您的所有文件都在一个文件夹中,这将可行。将我的路径更改为您的路径。
from os import listdir, remove
from os.path import isfile, join
mypath = 'D:\Files\Python\Output'
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
for f in onlyfiles:
if int(f.split('.')[1]) > 500:
remove(mypath+'\'+f)
在 python 中您可以尝试以下操作:
from pathlib import Path
p = Path('.')
for name in p.glob('*.[0-9]*'):
ext = name.suffix
if int(ext) > 500:
name.unlink()