2019-05-14
IO編程
文件讀寫
IO編程中,Stream(流)是一個(gè)很重要的概念,可以把流想象成一個(gè)水管,數(shù)據(jù)就是水管里的水,但是只能單向流動(dòng)。Input Stream就是數(shù)據(jù)從外面(磁盤、網(wǎng)絡(luò))流進(jìn)內(nèi)存,Output Stream就是數(shù)據(jù)從內(nèi)存流到外面去。
file=open('文件路徑','r',encoding='gbk') #讀取二進(jìn)制文件用‘rb’,讀取其他方式編碼的文件用encoding
file.read() #讀取文件全部?jī)?nèi)容
file.read(size) #每次最多讀取size個(gè)字節(jié)的內(nèi)容
file.readline() #可以每次讀取一行內(nèi)容
file.readlines() #一次性讀取所有內(nèi)容并按行返回list。
for line in f.readlines():
print(line.strip()) #把每行的空格去掉
file2=open('','r',encoding='',errors='ignore')
file2.write('Hello,world!')
file2.close()
StringIO和BytesIO
在內(nèi)存中讀取數(shù)據(jù)
from io import StringIO
f=StringIO()
f.write('Helllo')
f.write(' ')
f.write('world')
print(f.getvalue()) #getvalue()方法用于獲得寫入后的str
f=StringIO('Hello!\nHi!\nGoodbye!')
while True:
s=f.readline()
if s==''
break
print(s.strip())
from io import BytesIO
f=BytesIO()
f.write('中文'.encode('utf-8'))
print(f.getvalue())
<font color='maroon'>StringIO和BytesIO是在內(nèi)存中操作str和bytes的方法,使得和讀寫文件具有一致的接口。</font>
操作文件和目錄
Python的os模塊封裝了操作系統(tǒng)的目錄和文件操作,要注意這些函數(shù)有的在os模塊中,有的在os.path模塊中。
import os
os.name #操作系統(tǒng)類型
os.uname() #獲取詳細(xì)的系統(tǒng)信息
os.environ #在操作系統(tǒng)中定義的環(huán)境變量,全部保存在os.environ這個(gè)變量中,他返回一個(gè)dict
os.environ.get('PATH')
os.path.abspath('.') #查看當(dāng)前目錄的絕對(duì)路徑
os.path.join('','') #在某個(gè)目錄下創(chuàng)建一個(gè)新目錄,首先把新目錄的完整路徑表示出來
os.mkdir('') #創(chuàng)建一個(gè)目錄
os.rmdir('') #刪除一個(gè)目錄
os.path.split('/Users/michael/testdir/file.txt') #把一個(gè)路徑拆分為兩部分
('/Users/michael/testdir', 'file.txt')
os.path.splittext('/path/to/file.txt')
('/path/to/file', '.txt')
JSON!!!!
JSON表示出來就是一個(gè)字符串,可以被所有語言讀取,也可以方便地存儲(chǔ)到磁盤或者通過網(wǎng)絡(luò)傳輸。
- JSON類型???python類型
- {}????????dict
- []?????????list
- "string"??????str
- 1234.56?????int或float
- true/false????True/Flase
- null????????None
JSON格式和Python格式互相轉(zhuǎn)換</br>
1.將python轉(zhuǎn)化為JSON格式
import json
d=dict{name='Bob',gender='man',score=59,age=17}
json.dumps(d)
'{"age": 20, "score": 88, "name": "Bob"}'
dumps()方法返回一個(gè)str,內(nèi)容是標(biāo)準(zhǔn)的JSON</br>
dump()可以直接把JSON寫入一個(gè)file-like Object
2.將JSON轉(zhuǎn)化為Python格式
json_str='{"age": 20, "score": 88, "name": "Bob"}'
json.loads(json_str)
{"age": 20, "score": 88, "name": "Bob"}
要把JSON反序列化為Python對(duì)象,用loads()或者對(duì)應(yīng)的load()方法,前者把JSON的字符串反序列化,后者從file-like Object中讀取字符串并反序列化
3.json進(jìn)階
import json
class Student(object):
def _init_(self,name,age,score)
self.name=name
self.age=age
self.score=score
def student2dict(self):
return {
'name':self.name
'age':self.age
'score':self.score
}
def dict2student(d):
return Student(d['name',d['age'],d['score']])
s=Student('Bob',17,59)
print(json.dumps(s.student2dict()))
json_str='{"age": 20, "score": 88, "name": "Bob"}'
print(json.loads(json_str,object_hook=dict2student))