2017-01-23 69 views
0

以下是代码写入文件在python

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

下创建上传节我曾尝试创建两个文件的文件。第二个文件用于存储密文,以便我可以在第一个开关的情况下传递它。但是写入第二个文件不会发生。但是,如果我将一段代码的以下片段复制并粘贴到一个新的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。

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

+0

您不必手动“提升StopIteration”,即在任何生成器结束时自动完成。另外推荐的做法是把你所有的进口放在代码顶部 – Copperfield

回答

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.flush()后就可以

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

权从一个单独的终端检查您的文件。但是,在你的情况下,它会更好地close()它。

+0

非常感谢!它像一个魅力:) – mounika