文件重命名/删除
我有一些像这样的文件 -
*.sss 和 *_passive.sss
如果我有一个名为 blah1.sss 和 blah1_passive.sss 的文件,我想删除 blah1.sss 并重命名 blah1_passive.sss。但是,如果我没有 blah1_passive.sss,我想记录文件名并保留 blah1.sss。
我能够找到所有 *_passive.sss 文件,但我想知道可以将 *_passive.sss 重命名为 *.sss 的 awk/sed 等命令。
编辑:现在我有这个,但 os.rename 不会覆盖文件,但我需要它来覆盖。
import os, fnmatch
def locate(pattern, root=os.curdir):
#ignore directories- uncomment to make ignore work
#ignored = ["0201", "0306"]
for path, dirs, files in os.walk(os.path.abspath(root)):
#for dir in ignored: # if dir in dirs: #dirs.remove(dir)
for filename in fnmatch.filter(files, pattern):
yield os.path.join(path, filename)
for filename in locate("*_passive.sss"):
#found the files that i want to rename, but os.rename() refuses to overwrite !!
newfilename=filename.rstrip("_passive.sss") + ".sss"
os.rename(filename,newfilename)
I have a few files like this-
*.sss and *_passive.sss
If I have a file called blah1.sss and blah1_passive.sss, i want to get rid of blah1.sss and rename blah1_passive.sss. However, if I don't have blah1_passive.sss I want to log the filename and keep blah1.sss.
I was able to locate all the *_passive.sss files but I would like to know the awk/sed etc command that could rename the *_passive.sss to *.sss.
Edit: Right now i have this but os.rename does not overwrite files, i need it to overwrite though.
import os, fnmatch
def locate(pattern, root=os.curdir):
#ignore directories- uncomment to make ignore work
#ignored = ["0201", "0306"]
for path, dirs, files in os.walk(os.path.abspath(root)):
#for dir in ignored: # if dir in dirs: #dirs.remove(dir)
for filename in fnmatch.filter(files, pattern):
yield os.path.join(path, filename)
for filename in locate("*_passive.sss"):
#found the files that i want to rename, but os.rename() refuses to overwrite !!
newfilename=filename.rstrip("_passive.sss") + ".sss"
os.rename(filename,newfilename)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Unix 中,您可以在 Bourne shell 中使用以下命令(即
sh
/bash
):In Unix you can use the following command in a Bourne shell (i.e.
sh
/bash
):这个 shell 脚本应该可以解决这个问题:
还会向
missing.log
报告丢失的_passive
文件This shell script shoul do the trick:
also will report missing
_passive
files tomissing.log
这是一个Python解决方案:
Here's a python solution: