Python學習二------文件處理篇

預備工作
import os
os.chdir(r”c:….”)更改工作目錄
os.getcwd() 獲取當前工作目錄
文件處理
讀取mode=’r’
f=open(filename,mode)
a=f.readlines()
data=[]
for line in a:
line=line.strip() 去掉首尾空格和換行符
data_line =line.split(“\t”)
data.append(data_line)
f.close()
寫入 mode=’w’
write() 和read()都是字符串處理,如果寫入數字需要其他操作
f=open(filename,’w’)
datas=[[‘1’,’2’],[‘3’,’4’]]
line1=’,’.join(datas[0])
f.write(line1+’\n’)
如果datas=[[1,2],[3,4]]
for line in datas:
print>>>f,str(line[0])+’,’+str(line[1])+’\n’
f.close()

json的數據處理
對數據的序列化和反序列化
x=dict(height=170,weight=60)
y=json.dumps(x) 將字典x序列成了字符串y
json.loads(y) 還原成字典

如果是保存在文件中 或者從文件中讀取json數據
import json
x=dict(height=170,weight=60)
f=open(filename,’w’)
json.dump(x,f)
f.close()
f=open(filename,’rb’)
x=json.load(f)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章