四、文件的读写
# 四、文件的读写
# 4.1 python 内置方法
# 4.1.1 读
步骤:
- open
- read、readline、readlines
- close
try:
file = open('./chapter4/test.txt','r')
# lines = file.readlines()
# line = file.readline()
content = file.read()
print(content)
finally:
if file:
file.close()
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 4.1.2 写
写文件时,操作系统往往不会立刻把数据写入磁盘,而是放到内存缓存起来,空闲的时候再慢慢写入。
path = './chapter4/test.txt'
content = 'Nihao'
try:
f = open(path,'a')
f.write(content)
finally:
f.close()
1
2
3
4
5
6
7
2
3
4
5
6
7
# 4.1.3 open 方法
模式
- w
- r
- a 追加
# 4.2 Numpy
# 4.2.1 读写 csv、txt 文件
loadtxt,注意分隔符、编码等问题
import numpy as np
path = './chapter4/test.csv'
csv = np.loadtxt(path, delimiter=',')
print(csv)
1
2
3
4
2
3
4
import numpy as np
data = np.ones((3,3))
np.savetxt(fname='./chapter4/write.csv',X=data,delimiter=',',encoding='utf-8')
1
2
3
2
3
# 4.2.2 读写二进制文件
save
import numpy as np
arr = np.arange(10).reshape(2,5,1)
np.save('./chapter4/arr.npy', arr)
res = np.load('./chapter4/arr.npy')
print(res)
1
2
3
4
5
2
3
4
5
# 4.2.3 读写.dat
多维数据文件
import numpy as np
fileName = './chapter4/data.dat'
data = np.arange(30).reshape(5,2,3)
data.tofile(fileName,sep=',',format='%d')
newData = np.fromfile(fileName, dtype=np.int64, sep=',')
print(newData)
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 4.3 Pandas
处理 csv 文件
import pandas as pd
df = pd.read_csv('./chapter4/test.csv', header=None, delimiter=',')
df.to_csv('./chapter4/pandas_test.csv')
df.head()
1
2
3
4
2
3
4
处理 xlxs 文件
import pandas as pd
excel = pd.read_excel('./chapter4/table.xlsx', sheet_name='Sheet1', header=0)
excel.to_excel('./chapter4/pandas_table.xlsx',sheet_name='Sheet1')
excel.head()
1
2
3
4
2
3
4