python学习之元组与文件

python学习之元组与文件

元组

元组是最后一个python集合类型.元组由简单的对象构成,元组与列表非常相似,只不过元组不能在原处修改,并且通常写成圆括号,虽然元组部支持任何方法调用,但元组具有列表的大多数属性.

实际应用中的元组
元组的特殊语法:逗号和圆括号
如果圆括号里单一对象是元组对象而不是一个简单的表达式,需要对python进行特别说明,如果确实想要得到一个元组,只要在单一元素后面,圆括号之前加一个逗号就可以了,

>>>x = (40)   integer
>>>x
40

>>>x = (40,)  tuple
>>>x
(40,)

转换,方法以及不可变性

值得注意的是 +  * 以及分片操作应用于元组时,将会返回一个新数组,并且元组不提供字符串,列表和字典中的方法,

>>> t = ('cc','aa','dd','bb')
>>tmp = list(t)
>>>temp.sort()
>>>temp
['aa','bb','cc','dd']
>>> t = tuple(temp)
>>>t
('aa','bb','cc'.'dd')

列表解析也可以用于元组
>>>t = (1,2,3,4,5)
>>>l = [x+20 for x in t]
>>>l

[21,22,23,24,25]


index和count 也对元组进行了定义

>>> t = (1,2,3,2,4,2)

>>>t.index(2)    寻找第一次出现2的索引
1

>>>t.index(2,2)      在偏移2之后2出现的索引
3
>>>t.count(2)    2出现了多少次



元组的不可变性只适用于元组本身顶层,而非其内容,元组内部的列表还可以像往常那样修改
>>>t = (1,[2,3],4)
>>>t[1] = 'spam'
出错
>>>t[1][0] = 'spam'
>>>t
(1,['spam',3],4)


--------------------------------------------

文件

打开文件
程序内部调用open函数,首先是外不名,接着是处理模式,模式典型的用字符串r代表输入打开文件,w为输出打开文件,a代表在文件尾部追加内容打开文件,
1,在模式字符串尾加上b可以进行二进制数据处理

2,加上+意味着同时为输入和输出打开文件.


实际使用中

>>>myfile = open('myfile.txt','w')
>>>myfile.write('hello text file ')
>>>myfile.write('good bye text file ')
myfile.close();

>>>myfile = open('myfile.txt','r')
>>>myfile.readline()
'hello text file '
>>>myfile.readline()
'good bye text file '
>>>myfile.readline()        表明已经达到文件的尾部返回一个空的字符串
''


如果想把整个文件读入字符串然后打印

>>>open('myfile.txt','r').read()
'hello text filegood bye text file '

>>>print(open('myfile.txt').read())
hello text file
good bye text file

如果想要一行一行的扫描文本文件,这个往往是最佳选择
>>> for line in open('myfile','r')
    print(line ,end = '')

hello text file
good bye text file

当读取二进制文件的时候,得到一个bytes对象,
>>>data = open('data.bin','rb').read()
>>>data
b 'x00x00x00x07spamx00x08'
在文件中存储并解析python对象

>>>x,y,z = 43,44,45
>>>s = 'spam'
>>>d = {'a:1','b':2}
>>>l = [1,2,3]

>>>f = open('datafile.txt','w')
>>>f.write(s+' ')
>>>f.write('%s,%s.%s ' %(x,y,z))
>>>f.write(str(l)+'$'+str(d)+' ')
>>>f.close()


>>>chars = open('datafile.txt','r').read()
>>>print(chars)
spam
43,44,45
[1,2,3]${'a':1,'b':2}


>>>f = open('datafile.txt')
>>>line = readline()
>>line
'spam '
>>>line.rstrip()  移除尾部的换行符
'spam'

>>>line = readline()
'43,44,45 '
>>>parts = line.split(',')
>>>parts
['44','44',45']

>>>number = [int(p) for p in parts]
>>>number
[43,44,45]


使用pickle 存储python的原生对象

pickle 模块是能够让我们直接在文件中存储几乎任何python对象的高级工具,并不要求我们讲字符串转来转去

>>>d = {'a':1,'b':2}
>>> f = open('datafile.pkl','wb')
>>>import pickle
>>>pickle.dump(d,f)
>>>f.close()

如果想要取回字典时,只要在pickle重建一次

>>>f = open('datafile.pkl','rb')
>>>d = pickle.load(f)
>>>d
{'a':1,'b':2}