python基礎—文件 | json序列化


下面這些代碼沒有經過試驗, 只是作爲代碼段作爲日後的參考, 這些死的api姑且放在這裏用的時候看一下再做總結


import sys
print(sys.path)

# ---------------文件----------------------------
# 第一種直接方式
file1 = open("test.txt")
file2 = open("output.txt", "w")  # w 表示 write (覆寫) r 表示 read  a 表示 append (追寫)
while True:
	line = file1.readline()
	file2.write('"' + line[:s] + '"' + ",")
	if not line:
		break
file1.close()
file2.close()

# read()  將文本文件所有行讀到一個字符串中
# readline() 一行一行的讀
# readlines() 將文本所有行讀到一個list中,每一行是list的一個元素

# 第二種  文件迭代器
file2 = open("output.txt", "w")
for line in open("test.txt"):
	file2.write('"' + line[:s] + '"' + ",")

# 第三種  文件上下文管理器
# 打開文件
with open("somefile.txt", "r") as f:
	data = f.read()

# loop 整個文檔
with open("somefile.txt", "w") as f:
	for line in f:
		#  處理每一行

# 寫入文本
with open("somefile.txt", "w") as f:
	f.write("xxx")
	f.write("xxx")

# 要把打印的line寫入文件中
with open("somefile.txt", "w") as f :
	print(line1, file=f)
	print(line2, file=f)

# 二進制文件讀寫
f = open("EDC.jpg", "rb")
print(f.read())  # 輸出\xff\xd8.... 十六進制表示的字節

# 任何非標準文本文件(py2標準是ASCII, py3是unicode),用二進制讀入文件,用.decode() 來解碼
f = open("DeGuangGuo.txt", "rb")
u = f.read().decode('DeyunCode')

# 文件和目錄的操作
# python調用內置的os模塊來調用操作系統的接口函數
import os
os.name  # posix == nix   nt == windows
os.uname()  # 查看具體信息

# 環境變量 存在os.environ中  是list

# 當前目錄的絕對路徑
os.path.abspath('.')
# 在某個目錄下創建一個新目錄,把新目錄表示出來
os.path.join('/Users/EDC', 'Pictures') # 得到是新路徑的字符串
# 創建目錄
os.mkdir('/Users/EDC/Pictures/')
# 刪除目錄
os.rmdir('/Users/EDC/Pictures')
# 拆分字符串
os.path.split('/Users/EDC/Pictures/AJ.avi') # 拆分爲倆部分, 後一部分爲最後級別的目錄或者文件
# ('/Users/EDC/Pictures/', 'AJ.avi')
# 得到文件擴展名
os.path.splitext('/Users/EDC/Pictures/AJ.avi')
# ('/Users/EDC/Pictures/AJ', '.avi')
# 文件重命名
os.rename('xxx.xx', 'bbb')
# 刪除文件
os.remove('xxx')

# 可以使用 Shutil來幫助我們搞定文件
# 列出當前目錄下的所有目錄
[x for x in os.listdir('.') if os.path.isDir(x)]
# 列出 .py文件
[x for x in os.listdir('.') if os.path.isDir(x) and os.path.splitext(x)[1] == '.py']


# 序列化 從內存存儲到硬盤或者傳輸的過程爲序列化  從硬盤到內存爲反序列
import pickle
d = dict(name='jack', age=23, score=60)
str = pickle.dumps(d) # 調用pickle的dumps函數進行序列化處理
print(str)

f = open("dump.txt", "wb")
pickle.dump(d, f)	# 將內容序列化寫到文件中
f.close()


# 反序列化
import pickle
f = open("dump.txt", "rb")
d = pickle.load(f)    # 調用load做反序列化
f.close()
print(d)
print('name is %s' % d['name'])

# python2 和3 裏面的pickle不一致,爲了保證和諧
try:
	import cPickle as pickle
except ImportError:
	import pickle

# json 序列化   使用json這個庫即可 
import json
d1 = dict(name='jack', age = 29, score=32)
str = json.dump(d1)  # 序列化

d2 = json.loads(str) # 反序列化


I'm fish, I'm on.

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