码迷,mamicode.com
首页 > 编程语言 > 详细

Python文件

时间:2017-09-07 14:49:47      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:结果   最大值   wordcount   nbsp   模式   efi   错误信息   str   with   

一、打开文件

open()函数

1.定义

open(name[,mode[,buffering]])      #name为文件名, mode模式和buffering缓冲为可选

2.解释定义

mode模式 ===》‘r‘,‘w‘,‘a‘,‘b‘,‘+‘分别为读、写、追加、二进制、读写

bufferring ===》 0或False-无缓冲,直接针对硬盘

                          1或True-有缓冲,使用内存代替硬盘

           大于1的数字-缓冲区的大小

                           任意负数-使用默认的缓冲区大小

3.例子

f=open(r‘C:\text\somefile.txt‘)        #打开某路径下的txt文件

二、三种标准的流

1.sys.stdin  数据输入标准源

2.sys.stdout  数据一般出现在屏幕上

3.sys.stderr   错误信息,如栈追踪

三、读和写

1.写入

f=open(‘file.txt‘,‘w‘)

f.write(‘Hello‘)           #所提供的参数string会被追加到文件中已存在部分的后面

f.write(‘world!‘)

f.close

2.读取

f=open(‘file.txt‘,‘r‘)          #可以省略r,因为r是默认的模式

f.read(4)             #读取四个字符,返回读取的值

f.read()              #读取剩余的字符,返回剩余的值

3.管道输出

在一个命令后面续写其他的多个命令,管道符号| 将一个命令的标准输出和下一个命令的标准输入连在一起

$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

4.读写行

x=f.readline()  读取一行,带数字参数则返回读取的字符的最大值

x=f.readlines()   读取文件的所有行并返回,x[0]为第一行内容

x=f.writelines()  所有的字符串写入文件   \r(mac)   \r\n(windows)符号用来换行 --------由os.linesep决定

5.关闭文件

方法1

f.close() 

方法2

with open(‘file.txt‘) as somefile:

  do_something(somefile)              #执行完with语句后会自动关闭文件

Python文件

标签:结果   最大值   wordcount   nbsp   模式   efi   错误信息   str   with   

原文地址:http://www.cnblogs.com/zz27zz/p/7489287.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!