Python学习笔记<文件操作>

python的文件操作容易上手,我选取了一些比较常用的。
Keep SImple

打开文件
和c有点相像

f=open('friend.cpp')
#会读取出来整个文件的内容(小心内存不够)
f.read()
f.close()

但是这并不是推荐的方式,因为这样有些繁琐
python提供了更好的方式:

with open('friend.cpp') as f:
    f.read()

逐行读取
readlines()可以返回包含了逐行内容的list。

with open('friend.cpp') as f:
    for i in f.readlines():
        print i

或者直接用f也行:

with open('friend.cpp') as f:
    for i in f:
        print i

但是这有一个问题。print自己会换行。可以这样去掉回车符。

with open('friend.cpp') as f:
    for i in f:
    #去掉结尾处的回车符
        print(i.strip())

写文件

a=[1,2,3]
with open('s','w') as f:
    #str将一个list转换为字符串
    f.write(str(a))

版权声明:本文为博主原创文章,转载请标明出处。

posted @ 2015-10-02 21:43  Fridge  阅读(121)  评论(0)    收藏  举报