【编程语言学习——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)

猜你喜欢

转载自blog.csdn.net/xiangshiyi0724/article/details/84937818