文件对象声明及基本操作
另一种数据格式:文件/文档
path1 = 'C:/Users/Hjx/Desktop/text.txt'
path2 = 'C:\\Users\\Hjx\\Desktop\\text.txt'
path3 = r'C:\Users\Hjx\Desktop\text.txt'
print(path1)
print(path2)
print(path3)
f = open(path2, 'r')
print(type(f))
print(f)
print(f.read())
print('读取完毕')
print(f.read())
print('读取为空')
f.seek(0)
print(f.read())
print('第二次读取')
f.close()
f = open(path2, 'r')
print(type(f))
print(f)
print(f.read())
print('读取完毕')
print(f.read())
print('读取为空')
f.seek(0)
print(f.read())
print('第二次读取')
f.close()
系统模块下的路径操作
os 模块:提供了非常丰富的方法用来处理文件和目录
import os
print(os.name)
print(os.getcwd())
print(os.listdir())
print(os.path.split('C:\\Users\\Hjx\\Desktop\\text.txt'))
print(os.path.exists('C:\\Users\\Hjx\\Desktop\\heheh.txt'))
print(os.path.exists('C:\\Users\\Hjx\\Desktop\\'))
os.chdir('C:\\Users\\Hjx\\Desktop\\' )
f2 = open('text.txt','r')
print(f2.read())
文件的读取与写入
os 模块:提供了非常丰富的方法用来处理文件和目录
f = open('C:\\Users\\Hjx\\Desktop\\text.txt', 'r')
print(f.read())
f.seek(0)
print(f.read(2))
f.seek(0)
print(f.readline())
print(f.readline())
print(f.readline(4))
f.seek(0)
for line in f.readlines():
print(type(line),line)
path = 'C:\\Users\\Hjx\\Desktop\\jiuba.txt'
f = open(path,'r')
m = []
n = 0
for line in f.readlines():
n += 1
st1 = line.split(':')
name = st1[0]
information = st1[1]
st2 = information.split(',')
lng = float(st2[0])
lat = float(st2[1])
ad = st2[2].strip()
data = [['name',name],['lng',lng],['lat',lat],['address',ad]]
m.append(dict(data))
print(m)
print('\n数据转换完成!总共转换%i个数据'%n)
path = 'C:\\Users\\Hjx\\Desktop\\test_write.txt'
f = open(path, 'w', encoding = 'utf8')
f.write('hello world!')
f.close()
path = 'C:\\Users\\Hjx\\Desktop\\'
f = open(path + 'test_write2.txt', 'w', encoding = 'utf8')
lst = ['a','b','c','d','e']
f.writelines(lst)
f.close()
path = 'C:\\Users\\Hjx\\Desktop\\'
f = open(path + 'test_write2.txt', 'w', encoding = 'utf8')
lst = ['a','b','c','d','e']
for i in range(len(lst)):
lst[i] = lst[i] + '\n'
f.writelines(lst)
f.close()
两个列表[1~10],[a~j],写入一个txt,变成以下格式
1,a
2,b
3,c
...
n = list(range(1,11))
v = ['a','b','c','d','e','f','g','h','i','j']
f = open( 'C:\\Users\\Hjx\\Desktop\\test_write3.txt', 'w', encoding = 'utf8')
m = []
for i in range(len(n)):
f.writelines([str(n[i]),',',v[i] + '\n'])
f.close()
print('finished!')
pickle模块的运用
pickle提供了一个简单的持久化功能。可以将对象以文件的形式存放在磁盘上。
python的pickle模块实现了基本的数据序列和反序列化
通过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去,永久存储
通过pickle模块的反序列化操作,我们能够从文件中创建上一次程序保存的对象。
pickle.dump() / pickle.load()
import pickle
data = {'a':[1,2,3,4], 'b':('string','abc'), 'c':'hello'}
print(data)
pic = open( 'C:\\Users\\Hjx\\Desktop\\data.pkl', 'wb')
pickle.dump(data,pic)
pic.close()
f = open( 'C:\\Users\\Hjx\\Desktop\\data.pkl', 'rb')
st = pickle.load(f)
print(st)