【编程语言学习——python】11文件读取

文件打开

open函数用来打开文件,
包含三个参数:文件路径、文件模式、缓冲。

模式
‘r’读模式
‘w’写模式
‘a’追加模式
‘b’二进制模式
‘+’读/写模式

基本文件操作

>>>f=open(r'C:\Users\Administrator\Desktop\test.txt')
>>> f.read(7)##读七个字符
'Welcome'
>>> f.read(4)
' to '
>>> f.close()
>>> f=open(r'C:\Users\Administrator\Desktop\test.txt')
>>> print f.read()
Welcome to this file
There in nothing here except
This stupid haiku
>>> f.close()
f=open(r'C:\Users\Administrator\Desktop\test.txt')
>>> f.readline()
'Welcome to this file\n'
>>> f.readline()##单行读取
'There in nothing here except\n'
>>> f=open(r'C:\Users\Administrator\Desktop\test.txt')
>>> f.readlines()##读取所有行
['Welcome to this file\n', 'There in nothing here except\n', 'This stupid haiku']
>>> f.close()
>>> f=open(r'D:\python11.txt','w')
>>> f.write('this\nis a\npen')##写文件
>>> f.close()
>>> f=open(r'D:\python11.txt')
>>> lines=f.readlines()
>>> f.close()
>>> f=open(r'D:\python111.txt','w')
>>> f.writelines(lines)##写入所有行
>>> f.close()

迭代

  • 普通迭代
    使用while/for循环来进行文件的迭代以方便读取。
>>> def process(string):
	print'Processing:',string
>>> f=open(r'D:\python11.txt')
>>> for char in f.read():
	process(char)##按字节
>>> f=open(r'D:\python11.txt')
>>> for line in f.readlines():
	process(line)##按行
  • 函数迭代
>>> import fileinput
>>> for line in fileinput.input(r'D:\python11.txt'):
	process(line)
  • 文件迭代器
    可以直接把文件作为迭代的对象。
>>> for line in open(r'D:\python11.txt'):
	process(line)
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值