python文件

文件迭代器是最好的讀取工具,從文本文件讀取文字的最佳方式就是根本不要讀取該文件

從文件讀取的數(shù)據(jù)回到腳本是一個(gè)字符串。

#close是通常選項(xiàng)。調(diào)用close會終止外部文件的連接。

創(chuàng)新互聯(lián)長期為近1000家客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對不同對象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺,與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為蘇家屯企業(yè)提供專業(yè)的網(wǎng)站建設(shè)、成都網(wǎng)站制作,蘇家屯網(wǎng)站改版等技術(shù)服務(wù)。擁有10年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開發(fā)。

文件總是緩沖并且是可查的

#寫進(jìn)文件
myfile = open('myfile.txt', 'w')
myfile.write('hello textfile\n')
myfile.write('goodbye text file\n')
myfile.close()

#讀取文件
myfile = open('myfile.txt')
print(myfile.readline())
print(myfile.readline())
print(myfile.readline())
#hello textfile

#goodbye text file

print(open('myfile.txt').read())
#hello textfile
#goodbye text file

#文件迭代器往往是最佳選擇
for line in open('myfile.txt'):
print(line,end='')
#hello textfile
#goodbye text file
#python3

文本文件內(nèi)容為常規(guī)的字符串,自動執(zhí)行Unicode編碼和解碼,默認(rèn)行末換行。

二進(jìn)制文件為一個(gè)特殊的bytes字符串

#python2

文本文件處理8位文本和二進(jìn)制數(shù)據(jù),有特殊的字符串類來處理unicodewenben

#python3中的區(qū)別源自于簡單文本和unicode文本并為一種常規(guī)的字符串
#因?yàn)樗械奈谋径际莡nicode,包括ascii和其他8位編碼
#文件中處理解析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 +'\n')
f.write('%s,%s,%s\n' % (x, y, z))
f.write(str(l) +'$' +str(d) + '\n')
f.close()

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

f = open('datafile.txt')
line = f.readline()
print(line)
#spam

line.rstrip()
print(line)
#spam

line = f.readline()
print(line)
#43,44,45

parts = line.split(',')
print(parts)
#['43', '44', '45\n']
print(int(parts[1])) # 44
numbers = [int(p) for p in parts]
print(numbers) # [43, 44, 45]
#int和一些其他的轉(zhuǎn)換方法會忽略旁邊的空白
line = f.readline()
print(line) # [1, 2, 3]${'a': 1, 'b': 2}
parts = line.split('$')
print(parts) # ['[1, 2, 3]', "{'a': 1, 'b': 2}\n"]
print(eval(parts[0])) # [1, 2, 3]
obj = [eval(p) for p in parts]
print(obj) # [[1, 2, 3], {'a': 1, 'b': 2}]

#用pickle存儲python原生對象
d = {'a':1, 'b':2}
f = open('datafile.pkl','wb')
import pickle
pickle.dump(d,f)
f.close()
f = open('datafile.pkl','rb')
e = pickle.load(f)
print(e) # {'a': 1, 'b': 2}
print(open('datafile.pkl','rb').read())
#b'\x80\x03}q\x00(X\x01\x00\x00\x00aq\x01K\x01X\x01\x00\x00\x00bq\x02K\x02u.'
#文件中打包二進(jìn)制數(shù)據(jù)的存儲于解析
#struct模塊能夠構(gòu)造和解析打包的二進(jìn)制數(shù)據(jù)

#要生成一個(gè)打包的二進(jìn)制數(shù)據(jù)文件,用wb模式打開它并將一個(gè)格式化字符串和幾個(gè)python
#對象傳給struct,這里用的格式化字符串指一個(gè)4字節(jié)整數(shù),一個(gè)包含4字符的字符串
#以及一個(gè)二位整數(shù)的數(shù)據(jù)包。這些都是按照高位在前的形式
f = open('data.bin','wb')
import struct
data = struct.pack('>i4sh',7,b'spam',8)
print(data)
f.write(data)
f.close()
#f = open('data.bin', 'rb')
#data = f.read()
#print(data)

values = struct.unpack('>i4sh',data)
print(values) # (7, b'spam', 8)

#其他文件工具
#標(biāo)準(zhǔn)流,sys模塊中預(yù)先打開的文件對象如sys.stdout
#os模塊中的描述文件
#socket。pipes。FIFO文件
#通過鍵開存儲的文件
#shell流,op.popen和subprocess.Popen

#重訪類型分類
#對象根據(jù)分類共享操作,如str,list,tuple都共享合并,長度,索引等序列操作
#只有可變對象可以原處修改
#文件導(dǎo)出的唯一方法
#對象分類

#對象類型 分類 是否可變

數(shù)字 數(shù)值 否

字符串 序列 否

列表 序列 是

字典 映射 是

元組 序列 否

文件 拓展 N/A

sets 集合 是

frozenset 集合 否

#bytearray 序列 是
l = ['abc', [(1,2),([3],4)],5]
print(l[1]) # [(1, 2), ([3], 4)]
print(l[1][1]) # ([3], 4)
print(l[1][1][0]) # [3]

#引用vs拷貝
x = [1,2,3]
l = ['a',x,'b']
print(l) # ['a', [1, 2, 3], 'b']
d = {'x':x,'y':2}
print(d) # {'x': [1, 2, 3], 'y': 2}
x[1] = 'surprise'
print(l) # ['a', [1, 'surprise', 3], 'b']
print(d) # {'x': [1, 'surprise', 3], 'y': 2}

x = [1,2,3]
l = ['a',x[:],'b']
print(l) # ['a', [1, 2, 3], 'b']
d = {'x':x[:],'y':2}
print(d) # {'x': [1, 2, 3], 'y': 2}
x[1] = 'surprise'
print(l) # ['a', [1, 2, 3], 'b']
print(d) # {'x': [1, 2, 3], 'y': 2}

import copy
l = [1,2,3]
d = {'a':1,'b':2}
e = l[:]
D = d.copy()

#比較,相等性,真值
l1 = [1,2,4]
l2 = [1,2,4]
print(l1 == l2, l1 is l2) # True False

s1 = 'spam'
s2 = 'spam'
print(s1 == s2, s1 is s2) # True True
a = 'a long strings qqq'
b = 'a long strings qqq'
print(a == b, a is b) # True True ......

d1 = {'a':1,'b':2}
d2 = {'a':1,'b':3}
print(sorted(d1.items()) < sorted(d2.items())) # True
print(sorted(d1.keys()) < sorted(d2.keys())) # False
print(sorted(d1.values()) < sorted(d2.values())) # True

真值 'spam' 1

假值 '' [] {} () 0.0 None

l = [None] *4
print(l) # [None, None, None, None]
print(type([1]) == type([])) # True
print(type([1]) == list) # True
print(isinstance([1],list)) # True
import types
def f():pass
print(type(f) == types.FunctionType) # True

#內(nèi)置的類型陷阱
#賦值生成引用,而不是拷貝
l = [1,2,3]
m = ['x',l,'y']
print(m) # ['x', [1, 2, 3], 'y']
l[1] = 0
print(m) # ['x', [1, 0, 3], 'y']
#為了避免這種問題,可以用分片來生成一個(gè)高級拷貝
l = [1,2,3]
m = ['x',l[:],'y']
l[1] = 0
print(m) # ['x', [1, 2, 3], 'y']

重復(fù)能增加層次深度

l = [4,5,6]
x = l 3
y = [l]
3
print(x) # [4, 5, 6, 4, 5, 6, 4, 5, 6]
print(y) # [[4, 5, 6], [4, 5, 6], [4, 5, 6]]
l[1] = 0
print(x) # [4, 5, 6, 4, 5, 6, 4, 5, 6]
print(y) # [[4, 0, 6], [4, 0, 6], [4, 0, 6]]

留意循環(huán)數(shù)據(jù)結(jié)構(gòu)

l = ['grail']
l.append(l)
print(l) # ['grail', [...]]
#不可變類型不可再原處修改
t = (1,2,3)
t = t[:2] + (4,)
print(t) # (1, 2, 4)

名稱欄目:python文件
網(wǎng)站網(wǎng)址:http://muchs.cn/article8/jpihip.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站收錄軟件開發(fā)、微信公眾號、微信小程序、網(wǎng)站策劃網(wǎng)站改版

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站建設(shè)