官方文档:读写文件
一般读写步骤:
# -*- 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()