python 文件操作

1

open 第三个参数是 是否缓冲。False 无缓冲,直接操作硬盘。 True 操作内存,速度快。flash或close 才会更新硬盘数据

>>> f = open('somefile.txt', 'w')
>>> f.write("hello. ")
7
>>> f.write("World!")
6
>>> f.close()
hello. World!

>>> f = open('somefile.txt', 'r')
>>> f.read(4)
'hell'
>>> f.read()
'o. World!'
不提供数字,读取所有的文件。

2.

seek和tell

>>> f = open('somefile.txt', 'r')
>>> f.read(4)
'hell'
>>> f.read()
'o. World!'
>>> f=open(r'somefile.txt', 'w')
>>> f.write('01234567890123456789')
20
>>> f.seek(5)
5
>>> f.write('Hello, World')
12
>>> f.close()
>>> f = open(r'somefile.txt')
>>> f.read()
'01234Hello, World789'
>>> f = open(r'somefile.txt')
>>> f.read(3)
'012'
>>> f.read(2)
'34'
>>> f.tell()
5


3

file.readline:从当前读到下一个换行符,也包括这个换行符

比如:somefile.readline() 返回 ‘Hello wrold\n’

somefile.readline(5)返回‘Hello’

readlines 读取一个文件的所有行。返回list。


writelines和 readlines 相反。传入一个字符串list。不会增加新行,需自己添加。没有writelien,因为有write。

>>> f = open('somefile.txt','w')
>>> f.write('this\n is no\nhaiku')
17
>>> f.close()
this
 is no
haiku

换行符需respect 平台。so.linesep

如果希望不关闭继续使用,但是还想更新到硬盘上,用flash。

>>> import fileinput
>>> for line in fileinput.input(filename):
	process(line)


4.迭代文件

>>> f = open('somefile.txt')
>>> for line in f:
	print(line)

	
this

 is no

haiku
有空行:

>>> f = open('somefile.txt')
>>> for line in f:
	print(list(line))

	
['t', 'h', 'i', 's', '\n']
[' ', 'i', 's', ' ', 'n', 'o', '\n']
['h', 'a', 'i', 'k', 'u']
>>> f.close()
有时没有显式的关闭file,但是只要没有向文件写入内容,不关闭也是可以的。
>>> for line in open('somefile.txt'):
	print(line)

	
this

 is no

haiku

>>> f = open('somefile.txt', 'w')
>>> f.write('fl\n')
3
>>> f.write('sl\n')
3
>>> f.write('tl\n')
3
>>> f.close()
>>> lines = list(open('somefile.txt'))
>>> lines
['fl\n', 'sl\n', 'tl\n']
>>> f,s,t=open('somefile.txt')
>>> f
'fl\n'
>>> s
'sl\n'
>>> t
'tl\n'
>>> print(open('somefile.txt'))
<_io.TextIOWrapper name='somefile.txt' mode='r' encoding='cp936'>
open返回一个迭代器。

print向文件写入内容,会在string后面增加新的行。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值