python(一):文件操作

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值