我想创建一个函数user_dialogue(),要求输入两个文件的名称。该函数需要处理诸如IOError之类的错误。然后,这两个文件应通过我创建的另一个函数(称为加密函数)运行。
程序应该像这样工作:
新加密文件的名称:out_file.txt
要加密的文件名:blah.txt
导致错误!请重试。
要加密的文件名:我的file.csv
加密已完成!
到目前为止,这是我的代码:
ImportError: No module named openpyxl
user_dialogue()
这是我的函数crypto_file:
def user_dialogue():
file1 = open(input("New name of file: "), 'w')
done = False
while not done:
try:
file2 = open(input("Name of file that you want to encrypt: "), 'r')
except IOError as error:
print("File doesn't exist! The error is of the type: ", error)
else:
file2.close()
done = True
encrypt_file(file2,file1)
由于某种原因,该代码无法正常工作!有什么帮助吗?
答案 0 :(得分:0)
使用上下文管理器with
:
def user_dialogue():
try:
with open(input("Name of file that you want to encrypt: "), 'r') as file2:
try:
with open(input("New name of file(encrypted): "), 'w') as file1:
encrypt_file(file2, file1)
except IOError as e3:
print('No access')
except FileNotFoundError as e1:
print('No such file')
except IOError as e2:
print('No access')
def encrypt_file(in_file, out_file):
fileread = in_file.read()
encryptedfile = text_encryption_function.encrypt(fileread)
out_file.write(encryptedfile)
使用try / except:
def user_dialogue():
try:
file2 = open(input("Name of file that you want to encrypt: "), 'r')
try:
file1 = open(input("New name of file(encrypted): "), 'w')
encrypt_file(file2, file1)
except IOError as e3:
print('No access')
else:
file1.close()
except FileNotFoundError as e1:
print('No such file')
except IOError as e2:
print('No access')
else:
file2.close()
def encrypt_file(in_file, out_file):
fileread = in_file.read()
encryptedfile = text_encryption_function.encrypt(fileread)
out_file.write(encryptedfile)