Запись в файл в 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.
Я не понимаю, почему это не работает в первом случае, но работает во втором.
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()
Это.