f1 = open('file1.txt', 'r')# 以读模式打开文件
f2 = open('file2.txt', 'w')# 以写模式打开文件
当对文件内容操作完以后,一定要关闭文件对象,这样才能保证所做的任何修改都确实被保存到文件中。
f1.close()
with语句的用法如下:
with open(filename, mode, encoding) as fp:
使用pickle模块
import pickle
i = 13000000
a = 99.056
s ='中国人民123abc'
lst =[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
tu =(-5, 10, 8)
coll ={4, 5, 6}
dic ={'a':'apple', 'b':'banana', 'g':'grape', 'o':'orange'}
data =[i, a, s, lst, tu, coll, dic]
with open('sample_pickle.dat', 'wb') as f:
try:
pickle.dump(len(data), f)#表示后面将要写入的数据个数for item in data:
pickle.dump(item, f)
except:
print('写文件异常!')#如果写文件异常则跳到此处执行
使用struct模块
import struct
with open('sample_struct.dat', 'rb') as fp:
sn = fp.read(9)
tu = struct.unpack('if?', sn)
print(tu)
n, x, bl = tu
print('n=', n)
print('x=', x)
print('bl=', bl)
s = fp.read(9).decode()
print('s=', s)