Python学习笔记<文件操作>

来源:互联网 发布:阿里数据包导入淘宝 编辑:程序博客网 时间:2024/05/17 08:20

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))
0 0