python基础教程学习笔记十一

文件和素材

 

1 打开文件

    打开文件的语法:

Open(name[,mode[,buffering]])

Name 文件名

Mode 模式

Buffering 缓冲参数

示例代码如下:

>>> f=open(r'C:log.txt')

 

#文件不存在

>>> f=open(r'C: .txt')

Traceback (most recent call last):

  File "<pyshell#1>", line 1, in <module>

    f=open(r'C: .txt')

IOError: [Errno 2] No such file or directory: 'C:\t.txt'

      

文件模式

R  读模式

W 写模式

A 追加模式

B 二进制模式

+ 读写模式

 

缓冲

0/false  无缓冲

1/true  有缓冲(只有使用flush或是colse时才会更新硬盘上的数据)

大于1的数字表式缓冲区的大小

-1/任何负数  表示使用默认缓冲区大小

 

2 基本文件方法

读和写

//写文件

>>> f=open('c:pythonFile.txt','w')

>>> f.write('hello')

5

>>> f.write(',world')

6

>>> f.close()

 

//读文件

>>> f=open('c:pythonFile.txt','r')

>>> f.read(5)

'hello'

>>> f.read()

',world'

 

 

管式输出

 

#word count

import sys

text=sys.stdin.read()

words=text.split()

wordcount=len(words)

print('WordCount:',wordcount)

 

#cmd下测试

//文件的内容为

D:workspace_python>cat /cygdrive/c/pythonFile.txt

hello,world hi,this that

 

D:workspace_python>cat /cygdrive/c/pythonFile.txt|wordcount.py

WordCount: 3

 

读写行

File.readline

 

 

关闭文件

File.close()

也可以使用with语句

With open(‘c:pythonFile.txt’) as somefile

Dosomething(somefile)

 

使用基本文件方法

读:read(n)

Read()

Readlines()

写:write(string)

Write(list)

 

3 对文件内容进行迭代

按字节处理

Def process(string):

Print(‘processing’,string)

 

F=open(filename)

Char=f.read(1)

While char:

Process(char)

Char=f.read(1)

F.close()

 

#方式二

F=open(filename)

While true:

Char=f.read(1)

If not char:break

Process(char)

F.close()

 

按行操作

F=open(filename)

While true:

Line=f.readline()

If not line:break()

Process(line)

F.close()

 

读取所有内容

F=open(filename)

For char in f.read():

Process(char)

F.close()

 

F=open(filename)

For line in f.readlines():

Process(line)

F.close()

 

 

 

使用fileinput实现懒惰行迭代

Import fileinput

For line in fileinput(filename):

Process(line)

 

文件迭代器

F=open(filename)

For line in f:

Process(line)

F.close()

原文地址:https://www.cnblogs.com/retacn-yue/p/6194200.html