在python中写入文件

时间:2017-01-23 15:30:11

标签: python encryption writetofile

以下是代码

import sys
print "Enter '1' to upload a file." +'\n'
print "Enter '2' to download a file." +'\n'
print "Enter '3' to view the contents of a file" +'\n'
print "Enter '4' to delete the file" +'\n'
print "Enter '0' to exit"

class switch(object):
    def __init__(self, value):
        self.value = value
        self.fall = False

    def __iter__(self):
        """Return the match method once, then stop"""
        yield self.match
        raise StopIteration

    def match(self, *args):
        """Indicate whether or not to enter a case suite"""
        if self.fall or not args:
            return True
        elif self.value in args: # changed for v1.5, see below
            self.fall = True
            return True
        else:
            return False

import swiftclient
auth_url =  "https://identity.open.softlayer.com"+"/v3"
project_id = "307dc262d1e548848fa0207e217d0b16"
user_id = "7cb8aa19292c41d7a14709f428a5e8ff"
region_name = "dallas"
conn = swiftclient.Connection(key="B1.~QWR4rXG?!n,_",
authurl=auth_url,
auth_version='3',
os_options={"project_id": project_id,
"user_id": user_id,
"region_name": region_name})
container_name = 'new-container'

# File name for testing
file_name = 'example_file.txt'

# Create a new container
conn.put_container(container_name)
print "nContainer %s created successfully." % container_name

# List your containers
print ("nContainer List:")
for container in conn.get_account()[1]:
    print container['name']
# Create a file for uploading
from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
#print "asasa",cipher_suite

f=open("local.txt",'r')
content=f.read()
cipher_text = cipher_suite.encrypt(content)
print cipher_text
d=open("sample.txt",'w')
d.write(cipher_text)

while(1):
    v=raw_input("enter your input")


    for case in switch(v):

        if case('1'):
            print "upload a file"
            with open("sample.txt", 'r') as example_file:
                conn.put_object(container_name,
                file_name,
                contents= example_file.read(),
                content_type='text/plain')
                print "file uploaded successfully"
            break
        if case('2'):
            print "download a file"
            obj = conn.get_object(container_name, file_name)
            with open(file_name, 'w') as my_example:
                my_example.write(obj[1])
                print "nObject %s downloaded successfully." % file_name
            break
        if case('3'):

            print ("nObject List:")
            for container in conn.get_account()[1]:
                for data in conn.get_container(container['name'])[1]:
                    print 'object: {0}t size: {1}t date: {2}'.format(data['name'], data['bytes'], data['last_modified'])
            break
        if case('4'):
            print delete
            conn.delete_object(container_name, file_name)
            print "nObject %s deleted successfully." % file_name
            conn.delete_container(container_name)
            print "nContainer %s deleted successfully.n" % container_name

            break
        if case('0'):
            exit(0)
            break
        if case(): # default, could also just omit condition or 'if True'
            print "something else!"

在创建上传文件部分下,我尝试创建两个文件。第二个文件用于存储密文,以便我可以在第一个switch case中传递它。但是没有写入第二个文件。但是如果我将一段代码复制并粘贴到一个新的Python文件中并尝试执行它,它工作正常。

from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
#print "asasa",cipher_suite
f=open("local.txt",'r')
content=f.read()
cipher_text = cipher_suite.encrypt(content)
print cipher_text
d=open("sample.txt",'w')
d.write(cipher_text)

加密文本正在写入sample.txt。

我不明白为什么它在第一种情况下不起作用,但在第二种情况下工作。

1 个答案:

答案 0 :(得分:1)

您希望从同一个文件中读取:with open("sample.txt", 'r') as example_file。所以请先关闭它。

d=open("sample.txt", 'w')
d.write(cipher_text)
d.close()

或者

with open("sample.txt", 'w') as d:
    d.write(cipher_text)

顺便说一句,如果您想在写完后立即查看文件中的内容,则必须将其刷新:

d=open("sample.txt", 'w')
d.write(cipher_text)
d.flush()
while(1):
    v=raw_input("enter your input")

d.flush()之后,您可以从单独的终端检查您的文件。但同样,在你的情况下,close()它会更好。