1 文件操作
my_file=open('my file.txt','w') #用法: open('文件名','形式'), 其中形式有'w':write;'r':read.
my_file.write(text) #该语句会写入先前定义好的 text
my_file.close() #关闭文件
""""
This is my first test.
This is the second line.
This the third line.
This is appended file.
""""
2 获取目录下的所有文件名
获取StatlogVehicleSilhouettes路径下的所有文件名
trainfile=listdir("./StatlogVehicleSilhouettes")
num=len(trainfile)
for i in range(0,num):
print(str(i)+":"+trainfile[i])
输出如下
$ python3 wyp_read_data.py
0:xaa.dat.txt
1:xae.dat.txt
2:xah.dat.txt
3:xad.dat.txt
4:xag.dat.txt
5:xaf.dat.txt
6:xai.dat.txt
7:xab.dat.txt
8:xac.dat.txt
3 一个加载文件内数据的案例
#加载数据
def datatoarray(fname):
arr=[]
temp_file = open(fname,"r+")
#获取本文件内的所有行
for thisline in temp_file:
temp_list = thisline[:-1].split(' ')
arr=npy.array(temp_list[0:19])
print(arr)
temp_file.close()
return arr
实际上
#加载数据
def datatoarray(fname):
arr=[]
temp_file = open(fname,"r+")
# 下面这一行,切片去掉换行符,再以‘ ’分割字符串 ,得到一个列表
arr = [i[:-1].split(' ')[0:19] for i in temp_file.readlines()]
#print(arr)
return arr