文件

官方文档:读写文件

一般读写步骤:

# -*- coding: utf-8 -*-
try:
    f = open('test.txt','r+') #打开文件,参数表目的
    f.write('hello,world')

    f.seek(0) #解决直接 f.read() <a target=_blank href="https://segmentfault.com/q/1010000000397712">乱码问题</a>
    print f.read() #一次性读取f里面的内容
finally:
    f.close() #记住一定要关闭文件
如果你需要将路径写到里面,最好使用r:open(r'c:\program\test.txt')

关于read(), readline(),readlines():

要读取文件内容其实很简单,也许根本不用以上的三种方法都可以,比较一下:

# -*- coding: utf-8 -*-
import pprint
filename = 'test.txt'
#-----read()-----
f = open(filename)
for char in f.read():#遍历文件所有内容
    print 'this is read()',char
f.close()
#-----readline()-----
f = open(filename)
for i in range(3):#有三行,readline() 每次只读一行,
    print str(i)+f.readline()
f.seek(0) #将指针指回文件开头,否则下面的代码将读不到什么
for char in f.readline():#只能遍历一行中的字母
    print 'this is readline()',char
f.close()
#-----readlines()
f = open(r'test.txt')
pprint.pprint( f.readlines() ) #返回一个列表
f.seek(0) #将指针指回文件开头,否则下面的代码将读不到什么
for element in f.readlines():
    print 'this is readlines()',element
flist = list(open(r'test.txt'))
for element in flist:
    print 'this is open to list',element
f.close()

#-----直接循环遍历-----发现最方便
f = open(filename)
for line in f:
    print 'this is open',line
f.seek(0) #将指针指回文件开头,否则下面的代码将读不到什么
#same with above
for line in open(filename):
    print 'this is open',line
f.close()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值