博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 文件操作
阅读量:4221 次
发布时间:2019-05-26

本文共 1802 字,大约阅读时间需要 6 分钟。

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 nohaiku
有空行:

>>> 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 nohaiku
>>> 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后面增加新的行。

转载地址:http://mqmmi.baihongyu.com/

你可能感兴趣的文章
Openfiler 配置 NFS 示例
查看>>
Oracle 11.2.0.1 RAC GRID 无法启动 : Oracle High Availability Services startup failed
查看>>
Oracle 18c 单实例安装手册 详细截图版
查看>>
Oracle Linux 6.1 + Oracle 11.2.0.1 RAC + RAW 安装文档
查看>>
Oracle 11g 新特性 -- Online Patching (Hot Patching 热补丁)说明
查看>>
Oracle 11g 新特性 -- ASM 增强 说明
查看>>
Oracle 11g 新特性 -- Database Replay (重演) 说明
查看>>
Oracle 11g 新特性 -- 自动诊断资料档案库(ADR) 说明
查看>>
Oracle 11g 新特性 -- RMAN Data Recovery Advisor(DRA) 说明
查看>>
CSDN博客之星 投票说明
查看>>
Oracle wallet 配置 说明
查看>>
Oracle smon_scn_time 表 说明
查看>>
VBox fdisk 不显示 添加的硬盘 解决方法
查看>>
Secure CRT 自动记录日志 配置 小记
查看>>
RMAN RAC 到 单实例 duplicate 自动分配通道 触发 ORA-19505 错误
查看>>
mysql 随机分页的优化
查看>>
DB2快速创建测试库
查看>>
利用db2look查看ddl
查看>>
SD卡驱动分析--基于高通平台
查看>>
[图文] Seata AT 模式分布式事务源码分析
查看>>