如何在python中写入文本文件?

时间:2019-03-28 04:32:43

标签: python-3.x

我是使用python的初学者。我已经创建了一个纯文本文件,并且必须对其进行加密才能输出文件。但是我收到如下错误,无法将其写入输出文件。代码正在运行,但是创建了应加密的输出文件。

#!/usr/bin/env python3
import os
import binascii
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
import argparse

def readfile_binary(file):
with open(file, 'rb') as f:
content = f.read()   
return content

def writefile_binary(file, content):
with open(file, 'wb') as f:
f.write(content)

def main():
parser = argparse.ArgumentParser(description = 'Encryption and Decryption of the file')
parser.add_argument('-in', dest = 'input', required = True)
parser.add_argument('-out', dest = 'output', required = True)
parser.add_argument('-K', dest = 'key', help = 'The key to be used for encryption must be in hex')
parser.add_argument('-iv', dest = 'iv', help = 'The inintialisation vector, must be in hex')
args = parser.parse_args()

    input_content = readfile_binary(args. input)
    output_content = writefile_binary(args. output)

if __name__ == "__main__":
           main()

输出文件应该被加密,并且应该在目录中可用。

2 个答案:

答案 0 :(得分:0)

您可能需要更正代码的缩进。 Python需要在函数定义,循环等中缩进代码。

尝试一下:

#!/usr/bin/env python3
import os
import binascii
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
import argparse

def readfile_binary(file):
    with open(file, 'rb') as f:
        content = f.read()   
        return content

def writefile_binary(file, content):
    with open(file, 'wb') as f:
        f.write(content)

def main():
    parser = argparse.ArgumentParser(description = 'Encryption and Decryption of the file')
    parser.add_argument('-in', dest = 'input', required = True)
    parser.add_argument('-out', dest = 'output', required = True)
    parser.add_argument('-K', dest = 'key', help = 'The key to be used for encryption must be in hex')
    parser.add_argument('-iv', dest = 'iv', help = 'The inintialisation vector, must be in hex')
    args = parser.parse_args()

    input_content = readfile_binary(args. input)
    output_content = writefile_binary(args. output)

if __name__ == "__main__":
    main()

答案 1 :(得分:0)

这两行:

input_content = readfile_binary(args. input)
output_content = writefile_binary(args. output)

args.input中不能有空格。这是一个例子,

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('filename')
args = parser.parse_args()

# using type hints can help reasoning about code
def write(filename: str, content: str) -> None:
    with open(filename, 'wb') as f:
        f.write(str.encode(content))

# if the filename was successfully parsed from stdin
if args.filename == 'filename.txt':
    print(f"args: {args.filename}")

    # write to the appropriate output file
    write(filename=args.filename, content="content")