`

python入门笔记(四)

阅读更多
#文件
#1、打开文件
open(name[,mode[,buffering]])
f=open(r'/tmp/a.txt')
"""
r		读
w		写
a		追加
b		二进制(可添加到其他模块中使用),原样输出,且unix的\n和win的\r\n不会转换(python打开文本会默认转换)
+		读/写模式(可添加到其他模块中使用)

使用U参数,会将换行符全部转为\n
"""
#缓冲
#buffering参数,为0表示不使用缓冲,直接交互硬盘,否则表示缓存区的大小
#使用缓存区后,只有使用flush或close才能同步到硬盘
#2、读写
f=open('somefile.txt','w')
f.write('Hello, ')
f.write('World!')
f.close()
f=open('somefile.txt','r')
f.read(4)	#输出Hell
f.read()	#输出o,World	(剩余的字符)
f.close()
#3、光标
f.seek(5)#光标移动到5
f.seek(3,5)#光标移动到8
f.tell()#输出光标位置
#4、读写行
f.readline()
f.readline(5)#读一行前五个字符
f.readlines()
f.writelines(lines)
#5、文件关闭
#open
try:
	#todo
finally:
	f.close()
	
#python 2.5以后提供了专门的语句(todo之后会自动关闭文件,异常也会关闭),2.5以内版本使用with需要导入模块,from __future__ import with_statement
with open("aaa.txt") as f:
	#todo
#6、迭代
#惰性迭代
import fileinput
for line in fileinput.input(filename):
	process(line)
#文件迭代器
f=open(filename)
for line in f:
	process(line)
f.close()
lines=list(open('somefile.txt'))
a,b,c=open('somefile.txt')
#配置文件解析模块ConfigParser
"""
[messages]
greeting:welcome to xxx program!
"""
from ConfigParser import ConfigParser
CONFIGFILE="python.txt"
config=ConfigParser()
config.read(CONFIGFILE)
print config.get('messages','greeting')
#logging模块
import logging
logging.basicConfig(level=logging.INFO,filename='mylog.log')
logging.info('sometext')

	

 

1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics