我正在尝试使用下面的代码从目录中删除图像,但它没有按照我的意愿进行操作
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->createTable('messages', [
'id' => $this->primaryKey(),
'msg_from' => $this->integer(),
'msg_to' => $this->integer(),
'room' => $this->string(),
'message' => $this->text(),
'seen' => $this->smallInteger()->notNull()->defaultValue(0),
'created_at' => $this->string(),
'updated_at' => $this->string(),
]);
$this->addForeignKey('fk_msgFrom_messages_message_contacts', '{{%messages}}', 'msg_from', '{{%message_contacts}}', 'id', 'cascade', 'cascade');
$this->addForeignKey('fk_msgTo_message_contacts', '{{%messages}}', 'msg_to', '{{%message_contacts}}', 'id', 'cascade', 'cascade');
}
它不会引发任何错误,并且仍然无法删除文件
答案 0 :(得分:0)
尝试:
import os
import sys
count = 0
# Path for os.walk() is obtained via commandline parameter 1
for dirname, dirs, files in os.walk(sys.argv[1]):
for filename in files:
if filename.lower().endswith('.jpg'):
count += 1
thefile = os.path.join(dirname, filename)
os.remove(thefile)
print('Files:', count)
print('Files removed')
执行代码:-
-> ImageRemover.py "C:\Users\lol\Pictures"
执行脚本的常规语法= 'python_script_location' 'image_dir_location'
第二个参数将是图像文件目录的位置。
更改:-
删除了多余的最外层for
循环,仅提供了image_dir
到os.walk()
的路径,从而使过程更加高效。
要记住的事情:-
.png
扩展名,请将if filename.lower().endswith('.jpg')
更改为if filename.lower().endswith('.png')
确保使用命令行执行脚本,否则脚本将执行,但始终显示以下输出:-
文件:0
文件已删除