python 5 文件
文件读写&pickle&json&csv
#open & close
f = open("test.txt",'r')
i = 1
for line in f:
print(i,' ===> ',line)
i = i + 1
f.close()
#read 函数一次性读取文件的全部内容,以单个字符串形式返回全部文件
f = open("test.txt",'r')
contents = f.read()
for word in contents:
print(word)
f.close()
#realine函数逐行读取
f = open("test.txt",'r')
line1 = f.readline()
print(line1)
line2 = f.readline()
print(line2)
for l in f:#从readline结束的位置开始访问,有一个指针
print(l)
f.close()
#readlines 一次性读取多行,返回一个列表,每个元素是一行
f = open("test.txt",'r')
line = f.readlines()
print(line)
f.close()
#文件写入write writeline writelines
#r只读 w只写 a只写(追加)
#r+读写文件开始处 w+读写文件开始处 a+读写文件末尾
#wb rb 是读写二进制文件专用的
s = 'welcome\nchina'
f = open("test.txt",'w+')
f.write(s)
lines = f.readlines()
print(lines)
#文件路径
import os
print(os.getcwd())
path = "./code/tmp.txt" #当前目录下的code文件夹下的tmp
path = "../tmp.txt" #当前目录的父目录文件夹下的tmp
#捕获异常
try:
f = open("tedst.txt",'r')
for line in f:
pass
except:
print("file don't exist")
#pickle模块
import pickle
f = open('test.pkl','wb')
d = "Tsinghua"
pickle.dump(d,f)
f.close()
newf = open('test.pkl','rb')
newt = pickle.load(newf)
print(newt)
#json模块
import json
f = open('test.json','w')
d = "Tsinghua"
json.dump(d,f)
f.close()
newf = open('test.json','rb')
newt = json.load(newf)
print(newt)
#csv模块,逗号分隔值文件,可以将excel文件保存为CSV格式,进行逗号分隔
import csv
fcsv = open('test.csv','rU')
allcontent = []
csvobj = csv.reader(fcsv)
for l in csvobj:
allcontent.append(l)
for l in allcontent:
if l[0] != 'name':
l.append(int(l[1])*int(l[2]))
else:
l.append('乘积')
with open('test.csv','w') as writeobj:
writer = csv.writer(writeobj)
for r in allcontent:
writer.writerow(r)
with open('test.csv','r') as readobj:
csvread = csv.reader(readobj)
for l in csvread:
print(l)