python - 创建新文件的函数

标签 python python-3.x

我想创建一个函数 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/

相关文章:

python - 源 toastr 启动失败,错误启动 django 尽管它存在

python - 将值列表转换为编码变量?

python-3.x - 极地 : Naming Dataframe Columns when using scan_csv on headerless CSVs

python - 如何使用 Python 组合来自不同数组的 JSON 对象

python - 一种优雅/更快的方法来找到图像上线条的端点?

python - 如何在类中使用 lambda 作为方法?

python - OpenCV 或 Numpy 中的对比拉伸(stretch),具有限制和消隐

python - `xrange(2**100)` -> 溢出错误 : long int too large to convert to int

python - 使用smb协议(protocol)python3访问服务器上的远程文件

python - 将整数转换为 python 中的字节字符表示时的性能