python - 在 except 之后继续一个函数
问题描述
我有一个函数,它只是加密我在特定目录中的文件,我使用try
andexcept
来避免错误,如果有,我只想让我的函数继续,而不是退出程序。
我的功能是加入一个循环遍历我的文件,读取它们,然后加密数据并将密文写入文件,但我的问题是,如果出现错误,由于某种原因(无法写入文件等)。 ) 我的程序就停止了。
如果出现错误,如何防止我的程序破坏我的程序并继续使用该功能?
加密功能:
你可以看到我试图从files
函数中获取列表的长度,但它只是继续循环而不是停止。
def encrypt(self):
for i in range(0, len(files())):
try:
for file in files():
print(file)
with open(file, 'rb+') as f:
plain_text = f.read()
cipher_text = self.token.encrypt(plain_text)
f.seek(0); f.truncate()
f.write(cipher_text)
except Exception as e:
print(f'{e}')
文件功能:
这个函数只是获取我的文件并返回一个列表。
def files(pattern='*'):
matches = []
for root, dirnames, filenames in chain(os.walk(desktop_path), os.walk(downloads_path), os.walk(documents_path), os.walk(pictures_path)):
for filename in filenames:
full_path = os.path.join(root, filename)
if filter([full_path], pattern):
matches.append(os.path.join(root, filename))
return matches
解决方案
如果发生异常,您可以跳过该文件。
for file in files():
try:
with open(file, 'rb+') as f:
plain_text = f.read()
cipher_text = self.token.encrypt(plain_text)
f.seek(0); f.truncate()
f.write(cipher_text)
except Exception as e:
print(f'skipping file {file}. Reason: {e}')
推荐阅读
- android - 在前面板设置中禁用后,Android nougat 无法重新启用位置
- d3.js - 在具有可折叠树的 D3 v5 中平移没有响应
- django - 从 Django Rest Framework 和 Datatables 获取请求参数时出错
- c - 警告:内置函数 'strlen' int strlen (char *pstr) 的类型冲突;
- google-sheets-api - 使用 Google Sheets API 折叠组
- java - 从列表的开头和列表的结尾搜索(Java)
- java - 如何从具有多个参数的对象数组列表中出列?
- java - JVM 编译时间与代码缓存
- python - 如何打印内部列表同时包含字符串和字符串列表的列表列表?
- python - 用于读取文本文件并在 excel 中制表的 Python 程序