我想创建一个函数 user_dialogue() 来询问两个文件的名称。该函数需要处理IOError等错误。然后,这两个文件应该通过我创建的另一个函数运行,该函数称为“加密函数”。
程序应该像这样工作:
新加密文件的名称:out_file.txt
待加密文件名:blah.txt
这导致了一个错误!请重试。
要加密的文件名:my file.csv
加密完成!
这是我到目前为止的代码:
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)
用户对话()
这是我的函数 encrypt_file:
def encrypt_file(in_file, out_file):
fr = open(in_file, 'r')
fileread = fr.read()
encryptedfile = text_encryption_function.encrypt(fileread)
fr.close()
fw = open(out_file, 'a+')
fw.write(encryptedfile)
fw.close()
return in_file, out_file
由于某种原因,代码无法工作!请问有什么帮助吗?
最佳答案
使用上下文管理器与
:
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)
使用尝试/异常(exception):
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)
关于python - 创建新文件的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54655942/