python基础教程学习笔记十一

本文介绍了Python中文件的基本操作,包括文件的打开与关闭、读写模式的选择、缓冲机制的使用等,并提供了示例代码。此外,还介绍了如何通过不同方式遍历文件内容,如按字节、按行等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件和素材

1 打开文件

打开文件的语法:

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

Name 文件名

Mode 模式

Buffering 缓冲参数

示例代码如下:

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

#文件不存在

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

Traceback (most recent call last):

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

f=open(r'C:\t.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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值