苹果8怎样iphone传输照片到电脑脑

1594cqb 的BLOG
用户名:1594cqb
文章数:43
评论数:123
访问量:83556
注册日期:
阅读量:5863
阅读量:12276
阅读量:425059
阅读量:1113430
51CTO推荐博文
ZIP文件格式是一种常见的存档和压缩标准,这个zipfile模块提供了工具来创建、读取、写入、附加和列出一个ZIP文件。使用ZIP64扩展(即压缩文件大小超过4G),它能解压加密的ZIP文件,解密过程很慢。1、测试是否为ZIP文件is_zipfile()函数会返回一个布尔值来表示是否为ZIP文件,代码如下:#!/usr/bin/python
import zipfile
for filename in ['print_name.py', 'python.zip', 'uwsgi', 'admin']:
print '%20s %s' % (filename, zipfile.is_zipfile(filename))[root@www home]# python zipfile_is_zipfile.py
print_name.py False
python.zip True
uwsgi False
admin False#!/usr/bin/env python
import zipfile
zf = zipfile.ZipFile('python.zip', 'r')
print zf.namelist()[root@www home]# python zipfile_namelist.py
['test.txt']#import datetime
import zipfile
def print_info(archive_name):
zf = zipfile.ZipFile(archive_name)
for info list():
print info.filename
print '\tComment:\t', ment
print '\tModified:\t', datetime.datetime(*info.date_time)
print '\tSystem:\t\t', info.create_system, '(0 = Windows, 3 = Unix)'
print '\tZIP version:\t', info.create_version
print '\tCompressed:\t', press_size, 'bytes'
print '\tUncompressed:\t', info.file_size, 'bytes'
if __name__ == '__main__':
print_info('python.zip')[root@www home]# python zipfile_infolist.py
3 (0 = Windows, 3 = Unix)
ZIP version:
Compressed:
Uncompressed:
bytes#!/usr/bin/env python
import zipfile
zf = zipfile.ZipFile('python.zip')
for filename in ['test.txt', 'notthere.txt']:
info = zf.getinfo(filename)
except KeyError:
print 'ERROR: Did not find %s in zip file' % filename
print "%s is %d bytes" % (info.filename, info.file_size)[root@www home]# python zipfile_getinfo.py
test.txt is
ERROR: Did not find notthere.txt in zip file#!/usr/bin/env python
import zipfile
zf = zipfile.ZipFile('python.zip')
for filename in ['test.txt', 'notihere.txt']:
data = zf.read(filename)
except KeyError:
print 'ERROR: Did not find %s in zip file' % filename
print filename, ':'
print repr(data)
print[root@www home]# python zipfile_read.py
README.txt :
'The examples for the zipfile module use this file and example.zip as data.\n'
ERROR: Did not find notthere.txt in zip file#!/usr/bin/env python
from zipfile_infolist import print_info
import zipfile
print 'creating archive'
zf = zipfile.ZipFile('zipfile_write.zip', 'w')
print 'adding text.txt'
zf.write('text.txt')
print 'closing'
zf.close()
print_info('zipfile_write.zip')[root@www home]# python zipfile_write.py
creating archive
adding text.txt
3 (0 = Windows, 3 = Unix)
ZIP version:
Compressed:
Uncompressed:
bytes#!/usr/bin/env python
from zipfile_infolist import print_info
import zipfile
import zlib
compression = zipfile.ZIP_DEFLATED
compression = zipfile.ZIP_STORED
modes = { zipfile.ZIP_DEFLATED: 'deflated',
zipfile.ZIP_STORED:
print 'creating archive'
zf = zipfile.ZipFile('zipfile_write_compression.zip', mode='w')
print 'adding text.txt with compression mode', modes[compression]
zf.write('text.txt', compress_type=compression)
print 'closing'
zf.close()
print_info('zipfile_write_compression.zip')[root@www home]# python zipfile_write_compression.py
creating archive
adding text.txt with compression mode deflated
3 (0 = Windows, 3 = Unix)
ZIP version:
Compressed: 101923 bytes
Uncompressed:
bytes#!/usr/bin/env python
from zipfile_infolist import print_info
import zipfile
zf = zipfile.ZipFile('zipfile_write_arcname.zip', mode='w')
zf.write('text.txt', arcname='NOT_README.txt')
zf.close()
print_info('zipfile_write_arcname.zip')[root@www home]# python zipfile_write_arcname.py
NOT_README.txt
3 (0 = Windows, 3 = Unix)
ZIP version:
Compressed:
Uncompressed:
bytes更多博文请移步: 本文参考: & & & & &本文出自 “” 博客,请务必保留此出处
了这篇文章
类别:┆阅读(0)┆评论(0)编程开发子分类Python 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。Python语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。
本文是一个python实现的把txt文件转换为JSON格式输出示例代码,感兴趣的同学参考下。
简单的1-10存一个文件, A-J 存一个文件
import json &
book = 'C:\Python27\\book.txt' &
date = 'C:\Python27\date.txt' &
book_list = [] &
date_list = [] &
with open(book) as b: &
&&& book_list = b.read().splitlines() &
with open(date) as d: &
&&& date_list = d.read().splitlines() &
data = dict(zip(book_list, date_list)) &
print type(data) &
print data &
j = json.dumps(data) &
print type(j) &
很简单的先从本地中读取文件,然后用with关键词配合open方法打开文件。读取文件的时候忽略'\n',不然会在最终结果出现一对'\n':&\n&。
with open(fname) as f: &
&&& content = f.readlines()
会得到'\n'
with open(fname) as f: &
&&& content = f.read().splitlines()
不会得到'\n'
然后我们将两个list用zip方法组合,转换为dict字典类型,再用json.dumps方法转换为JSON格式输出。
&type 'dict'& &
{'A': '1', 'C': '3', 'B': '2', 'E': '5', 'D': '4', 'G': '7', 'F': '6', 'I': '9', 'H': '8', 'J': '10'} &
&type 'str'& &
{&A&: &1&, &C&: &3&, &B&: &2&, &E&: &5&, &D&: &4&, &G&: &7&, &F&: &6&, &I&: &9&, &H&: &8&, &J&: &10&}
首先我们看help(zip)
zip(...) &
&&& zip(seq1 [, seq2 [...]]) -& [(seq1[0], seq2[0] ...), (...)] &
&&& Return a list of tuples, where each tuple contains the i-th element &
&&& from each of the argument sequences.& The returned list is truncated &
&&& in length to the length of the shortest argument sequence.
zip接受一系列可迭代对象作为参数,讲对象中对应的元素打包成一个个tuple,然后返回由这些tuples组成的list。P.S. 如果传入的参数不等长,那么返回的list的长度和参数中长度最短的对象相同。
z1=[1,2,3] &
z2=[4,5,6] &
result = zip(z1,z2) &
print result &
z3=[4,5,6,7] &
result = zip(z1,z3) &
print result &
result = zip(*result) &
print result &
# result &
[(1, 4), (2, 5), (3, 6)] &
[(1, 4), (2, 5), (3, 6)] &
[(1, 2, 3), (4, 5, 6)]
配合*星号操作符,我们可以把zip的列表再解压,把初始的两个list还原出来以tuple形式展现。
高级应用例子
二维矩阵行列变换
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print [[row[col] for row in a] for col in range(len(a[0]))] &
# result &
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
或者利用zip配合map可以达到同样的效果
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] &
print zip(*a) &
print map(list,zip(*a)) &
# result &
[(1, 4, 7), (2, 5, 8), (3, 6, 9)] &
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
使用zip反转字典
m = {'a': 1, 'b': 2, 'c': 3, 'd': 4} &
print m.items() &
print zip(m.values(), m.keys()) &
mi = dict(zip(m.values(), m.keys())) &
print mi &
# result &
[('a', 1), ('c', 3), ('b', 2), ('d', 4)] &
[(1, 'a'), (3, 'c'), (2, 'b'), (4, 'd')] &
{'a': 1, 'c': 3, 'b': 2, 'd': 4} &
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
with statement
with的实质是一个控制流语句,可以用来简化try-finally语句。主要功能是实现一个类__enter__()和__exit__()方法
class controlled_execution: &
&&& def _enter__(self): &
&&&&&&& set things up &
&&&&&&& return thing &
&&& def __exit__(self, type, value,& traceback): &
&&&&&&& tear thing down &
with controlled_execution() as thing: &
&&& some code
在实际的运行过程中,首先运行enter里面的代码,返回thing,作为as之后的变量值,然后再与运行with模块中的代码,最后会自动执行exit中的代码,不论with中的代码运行结果如何。
这样也就简化了try-finally语句。同样用在读取文件的操作中,将文件的关闭操作放在exit方法中,就不会忘记释放文件而出现错误。
P.S. exit方法的返回值可以用来指示with部分的代码出现的异常是否需要raise,如果返回false,则会raise,否则,不进行操作。
此外,python库中有contextlib模块,使你不用构造含有__enter__和__exit__方法的类就可以使用with
&&& from contextlib import contextmanager&& &
&&& from __future__ import with_statement&& &
&&& @contextmanager&& &
... def context():&& &
...&&&& print 'entering the zone'&& &
...&&&& try:&& &
...&&&&&&&& yield&& &
...&&&& except Exception, e:&& &
...&&&&&&&& print 'with an error %s'%e&& &
...&&&&&&&& raise e&& &
...&&&& else:&& &
...&&&&&&&& print 'with no error'&& &
&&& with context():&& &
...&&&& print '----in context call------'&& &
entering the zone&& &
----in context call------&& &
with no error
from contextlib import closing&& &
import urllib&& &
with closing(urllib.urlopen('http://www.python.org')) as page:&& &
&&& for line in page:&& &
&&&&&&& print line
P.S. 在一个with后面,你可以open多个文件,比如
def filter(txt, oldfile, newfile): &
&&& '''''\
&&& Read a list of names from a file line by line into an output file.
&&& If a line begins with a particular name, insert a string of text
&&& after the name before appending the line to the output file.
&&& ''' &
&&& with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile: &
&&&&&&& for line in infile: &
&&&&&&&&&&& if line.startswith(txt): &
&&&&&&&&&&&&&&& line = line[0:len(txt)] + ' - Truly a great person!\n' &
&&&&&&&&&&& outfile.write(line) &
# input the name you want to check against &
text = input('Please enter the name of a great person: ')&&&& &
letsgo = filter(text,'Spanish', 'Spanish2')
Copyright &
All Rights Reserved &&&&&&随笔 - 895&
评论 - 129&
&&&&&&&&&&&
有时我们需要在&Python&中使用&zip&文件,而在1.6版中,Python&就已经提供了&zipfile&模块可以进行这样的操作。不过&Python&中的&zipfile&模块不能处理多卷的情况,不过这种情况并不多见,因此在通常情况下已经足够使用了。下面我只是对一些基本的&zipfile&操作进行了记录,足以应付大部分的情况了。
zipfile&模块可以让你打开或写入一个&zip&文件。比如:
import zipfile
z = zipfile.ZipFile('zipfilename', mode='r')
&&这样就打开了一个&zip&文件,如果mode为'w'或'a'则表示要写入一个&zip&文件。如果是写入,则还可以跟上第三个参数:
&&compression=zipfile.ZIP_DEFLATED&或
&&compression=zipfile.ZIP_STORED ZIP_DEFLATED是压缩标志,如果使用它需要编译了zlib模块。而后一个只是用zip进行打包,并不压缩。
在打开了zip文件之后就可以根据需要是读出zip文件的内容还是将内容保存到&zip&文件中。
读出zip中的内容
很简单,zipfile&对象提供了一个read(name)的方法。name为&zip文件中的一个文件入口,执行完成之后,将返回读出的内容,你把它保存到想到的文件中即可。
写入zip文件
有两种方式,一种是直接写入一个已经存在的文件,另一种是写入一个字符串。
对&于第一种使用&zipfile&对象的&write(filename, arcname, compress_type),后两个参数是可以忽略的。第一个参数是文件名,第二个参数是表示在&zip&文件中的名字,如果没有给出,表示使用与filename一样的名字。compress_type是压缩标志,它可以覆盖创建&zipfile&时的参数。第二种是使用&zipfile&对象的&writestr(zinfo_or_arcname, bytes),第一个参数是zipinfo&对象或写到压缩文件中的压缩名,第二个参数是字符串。使用这个方法可以动态的组织文件的内容。
需要注意的是在读出时,因为只能读出内容,因此如果想实现按目录结构展开&zip&文件的话,这些操作需要自已来完成,比如创建目录,创建文件并写入。而写入时,则可以根据需要动态组织在&zip&文件中的目录结构,这样可以不按照原来的目录结构来生成&zip&文件。
于是我为了方便使用,创建了自已的一个&ZFile&类,主要是实现象&winrar&的右键菜单中的压缩到的功能--即将一个zip文件压缩到指定目录,自动创建相应的子目录。再有就是方便生成&zip&文件。类源码为:
#&coding:cp936&&
#&Zfile.py&&
import&zipfile&&&
import&os.path&&&
import&os&&&
class&ZFile(object):&&&
&&&&def&__init__(self,&filename,&mode='r',&basedir=''):&&&
&&&&&&&&self.filename&=&filename&&&
&&&&&&&&self.mode&=&mode&&&
&&&&&&&&if&self.mode&in&('w',&'a'):&&&
&&&&&&&&&&&&self.zfile&=&zipfile.ZipFile(filename,&self.mode,&compression=zipfile.ZIP_DEFLATED)&&&
&&&&&&&&else:&&&
&&&&&&&&&&&&self.zfile&=&zipfile.ZipFile(filename,&self.mode)&&&
&&&&&&&&self.basedir&=&basedir&&&
&&&&&&&&if&not&self.basedir:&&&
&&&&&&&&&&&&self.basedir&=&os.path.dirname(filename)&&&
&&&&&&&&&&
&&&&def&addfile(self,&path,&arcname=None):&&&
&&&&&&&&path&=&path.replace('//',&'/')&&&
&&&&&&&&if&not&arcname:&&&
&&&&&&&&&&&&if&path.startswith(self.basedir):&&&
&&&&&&&&&&&&&&&&arcname&=&path[len(self.basedir):]&&&
&&&&&&&&&&&&else:&&&
&&&&&&&&&&&&&&&&arcname&=&''&&&
&&&&&&&&self.zfile.write(path,&arcname)&&&
&&&&&&&&&&&&&&
&&&&def&addfiles(self,&paths):&&&
&&&&&&&&for&path&in&paths:&&&
&&&&&&&&&&&&if&isinstance(path,&tuple):&&&
&&&&&&&&&&&&&&&&self.addfile(*path)&&&
&&&&&&&&&&&&else:&&&
&&&&&&&&&&&&&&&&self.addfile(path)&&&
&&&&&&&&&&&&&&
&&&&def&close(self):&&&
&&&&&&&&self.zfile.close()&&&
&&&&&&&&&&
&&&&def&extract_to(self,&path):&&&
&&&&&&&&for&p&in&self.zfile.namelist():&&&
&&&&&&&&&&&&self.extract(p,&path)&&&
&&&&&&&&&&&&&&
&&&&def&extract(self,&filename,&path):&&&
&&&&&&&&if&not&filename.endswith('/'):&&&
&&&&&&&&&&&&f&=&os.path.join(path,&filename)&&&
&&&&&&&&&&&&dir&=&os.path.dirname(f)&&&
&&&&&&&&&&&&if&not&os.path.exists(dir):&&&
&&&&&&&&&&&&&&&&os.makedirs(dir)&&&
&&&&&&&&&&&&file(f,&'wb').write(self.zfile.read(filename))&&&
&&&&&&&&&&&&&&
&&&&&&&&&&
def&create(zfile,&files):&&&
&&&&z&=&ZFile(zfile,&'w')&&&
&&&&z.addfiles(files)&&&
&&&&z.close()&&&
def&extract(zfile,&path):&&&
&&&&z&=&ZFile(zfile)&&&
&&&&z.extract_to(path)&&&
&&&&z.close()&&
阅读(...) 评论()

我要回帖

更多关于 照片实时传输到电脑 的文章

 

随机推荐