0

The following is the code

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!"

Under create a file for uploading section I have tried to create two files. The second file is for storing the ciphertext so that I could pass it in the 1st switch case.But writing to the second file isn't happening.However if I copy and paste the following segment of a code in a new Python file and try executing it, it is working fine.

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)

The encrypted text is being written to the sample.txt.

I don't understand why it isn't working in the first case, but is working in the second.

1
  • you don't have to raise StopIteration manually, that is done automatically at the end of any generator. Also the recommended practice is to put all yours imports at the top of your code Commented Jan 23, 2017 at 16:33

1 Answer 1

1

Looks like you want to read from the same file: with open("sample.txt", 'r') as example_file. So please close it before.

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

Or

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

BTW, if you want to see the content in a file right after you wrote, you have to flush it:

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

Right after d.flush() you can inspect your file from a separate terminal. But again, in your case it would be better to close() it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.