open(name[,mode[,buffering]]) #name为文件名, mode模式和buffering缓冲为可选
mode模式 ===》‘r‘,‘w‘,‘a‘,‘b‘,‘+‘分别为读、写、追加、二进制、读写
bufferring ===》 0或False-无缓冲,直接针对硬盘
1或True-有缓冲,使用内存代替硬盘
大于1的数字-缓冲区的大小
任意负数-使用默认的缓冲区大小
f=open(r‘C:\text\somefile.txt‘) #打开某路径下的txt文件
1.sys.stdin 数据输入标准源
2.sys.stdout 数据一般出现在屏幕上
3.sys.stderr 错误信息,如栈追踪
f=open(‘file.txt‘,‘w‘)
f.write(‘Hello‘) #所提供的参数string会被追加到文件中已存在部分的后面
f.write(‘world!‘)
f.close
f=open(‘file.txt‘,‘r‘) #可以省略r,因为r是默认的模式
f.read(4) #读取四个字符,返回读取的值
f.read() #读取剩余的字符,返回剩余的值
在一个命令后面续写其他的多个命令,管道符号| 将一个命令的标准输出和下一个命令的标准输入连在一起
$cat file.txt | python script.py | sort
cat file.tex【 标准输出(sys.stdout)】--->script.py读取【file.txt写入的】再输出【sys.stdout】--->sort得到script.py输出的数据,再输出
管道script.py 会从它的sys.stdin中读取数据(file.txt写入的),并把结果写入sys.stdout(sort在此得到数据)
-------------------------------------------------------------------------------------------------------------
file.txt 内容为 your mother was a hamster and your father smelled of elderberries.
script.py内容为
import sys
text=sys.sdin.read()
words=text.split()
wordcount=len(words)
print wordcount
执行 file.txt | python script.py 的结果为11
x=f.readline() 读取一行,带数字参数则返回读取的字符的最大值
x=f.readlines() 读取文件的所有行并返回,x[0]为第一行内容
x=f.writelines() 所有的字符串写入文件 \r(mac) \r\n(windows)符号用来换行 --------由os.linesep决定
f.close()
with open(‘file.txt‘) as somefile:
do_something(somefile) #执行完with语句后会自动关闭文件
原文:http://www.cnblogs.com/zz27zz/p/7489287.html