Python基础7:文件操作
[ 文件操作]
1 对文件操作流程
- 打开文件,得到文件句柄并赋值给一个变量
- 通过句柄对文件进行操作
- 关闭文件
现有文件如下:
- 昨夜寒蛩不住鸣。
- 惊回千里梦,已三更。
- 起来独自绕阶行。
- 人悄悄,帘外月胧明。
- 白首为功名,旧山松竹老,阻归程。
- 欲将心事付瑶琴。
- 知音少,弦断有谁听。
- f = open('小重山') #打开文件
- data=f.read()#获取文件内容
- f.close() #关闭文件
2 文件打开模式
- ========= ===============================================================
- Character Meaning
- --------- ---------------------------------------------------------------
- 'r' open for reading (default)
- 'w' open for writing, truncating the file first
- 'x' create a new file and open it for writing
- 'a' open for writing, appending to the end of the file if it exists
- 'b' binary mode
- 't' text mode (default)
- '+' open a disk file for updating (reading and writing)
- 'U' universal newline mode (deprecated)
- ========= ===============================================================
先介绍三种最基本的模式:
- # f = open('小重山2','w') #打开文件
- # f = open('小重山2','a') #打开文件
- # f.write('莫等闲1\n')
- # f.write('白了少年头2\n')
- # f.write('空悲切!3')
3 文件具体操作
- def read(self, size=-1): # known case of _io.FileIO.read
- """
- 注意,不一定能全读回来
- Read at most size bytes, returned as bytes.
- Only makes one system call, so less data may be returned than requested.
- In non-blocking mode, returns None if no data is available.
- Return an empty bytes object at EOF.
- """
- return ""
- def readline(self, *args, **kwargs):
- pass
- def readlines(self, *args, **kwargs):
- pass
- def tell(self, *args, **kwargs): # real signature unknown
- """
- Current file position.
- Can raise OSError for non seekable files.
- """
- pass
- def seek(self, *args, **kwargs): # real signature unknown
- """
- Move to new file position and return the file position.
- Argument offset is a byte count. Optional argument whence defaults to
- SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
- are SEEK_CUR or 1 (move relative to current position, positive or negative),
- and SEEK_END or 2 (move relative to end of file, usually negative, although
- many platforms allow seeking beyond the end of a file).
- Note that not all file objects are seekable.
- """
- pass
- def write(self, *args, **kwargs): # real signature unknown
- """
- Write bytes b to file, return number written.
- Only makes one system call, so not all of the data may be written.
- The number of bytes actually written is returned. In non-blocking mode,
- returns None if the write would block.
- """
- pass
- def flush(self, *args, **kwargs):
- pass
- def truncate(self, *args, **kwargs): # real signature unknown
- """
- Truncate the file to at most size bytes and return the truncated size.
- Size defaults to the current file position, as returned by tell().
- The current file position is changed to the value of size.
- """
- pass
- def close(self): # real signature unknown; restored from __doc__
- """
- Close the file.
- A closed file cannot be used for further I/O operations. close() may be
- called more than once without error.
- """
- pass
- ##############################################################less usefull
- def fileno(self, *args, **kwargs): # real signature unknown
- """ Return the underlying file descriptor (an integer). """
- pass
- def isatty(self, *args, **kwargs): # real signature unknown
- """ True if the file is connected to a TTY device. """
- pass
- def readable(self, *args, **kwargs): # real signature unknown
- """ True if file was opened in a read mode. """
- pass
- def readall(self, *args, **kwargs): # real signature unknown
- """
- Read all data from the file, returned as bytes.
- In non-blocking mode, returns as much as is immediately available,
- or None if no data is available. Return an empty bytes object at EOF.
- """
- pass
- def seekable(self, *args, **kwargs): # real signature unknown
- """ True if file supports random-access. """
- pass
- def writable(self, *args, **kwargs): # real signature unknown
- """ True if file was opened in a write mode. """
- pass
文件操作方法介绍
- f = open('小重山') #打开文件
- # data1=f.read()#获取文件内容
- # data2=f.read()#获取文件内容
- #
- # print(data1)
- # print('...',data2)
- # data=f.read(5)#获取文件内容
- # data=f.readline()
- # data=f.readline()
- # print(f.__iter__().__next__())
- # for i in range(5):
- # print(f.readline())
- # data=f.readlines()
- # for line in f.readlines():
- # print(line)
- # 问题来了:打印所有行,另外第3行后面加上:'end 3'
- # for index,line in enumerate(f.readlines()):
- # if index==2:
- # line=''.join([line.strip(),'end 3'])
- # print(line.strip())
- #切记:以后我们一定都用下面这种
- # count=0
- # for line in f:
- # if count==3:
- # line=''.join([line.strip(),'end 3'])
- # print(line.strip())
- # count+=1
- # print(f.tell())
- # print(f.readline())
- # print(f.tell())#tell对于英文字符就是占一个,中文字符占三个,区分与read()的不同.
- # print(f.read(5))#一个中文占三个字符
- # print(f.tell())
- # f.seek(0)
- # print(f.read(6))#read后不管是中文字符还是英文字符,都统一算一个单位,read(6),此刻就读了6个中文字符
- #terminal上操作:
- f = open('小重山2','w')
- # f.write('hello \n')
- # f.flush()
- # f.write('world')
- # 应用:进度条
- # import time,sys
- # for i in range(30):
- # sys.stdout.write("*")
- # # sys.stdout.flush()
- # time.sleep(0.1)
- # f = open('小重山2','w')
- # f.truncate()#全部截断
- # f.truncate(5)#全部截断
- # print(f.isatty())
- # print(f.seekable())
- # print(f.readable())
- f.close() #关闭文件
扩展文件操作模式:
- # f = open('小重山2','w') #打开文件
- # f = open('小重山2','a') #打开文件
- # f.write('莫等闲1\n')
- # f.write('白了少年头2\n')
- # f.write('空悲切!3')
- # f.close()
- #r+,w+模式
- # f = open('小重山2','r+') #以读写模式打开文件
- # print(f.read(5))#可读
- # f.write('hello')
- # print('------')
- # print(f.read())
- # f = open('小重山2','w+') #以写读模式打开文件
- # print(f.read(5))#什么都没有,因为先格式化了文本
- # f.write('hello alex')
- # print(f.read())#还是read不到
- # f.seek(0)
- # print(f.read())
- #w+与a+的区别在于是否在开始覆盖整个文件
- # ok,重点来了,我要给文本第三行后面加一行内容:'hello 岳飞!'
- # 有同学说,前面不是做过修改了吗? 大哥,刚才是修改内容后print,现在是对文件进行修改!!!
- # f = open('小重山2','r+') #以写读模式打开文件
- # f.readline()
- # f.readline()
- # f.readline()
- # print(f.tell())
- # f.write('hello 岳飞')
- # f.close()
- # 和想的不一样,不管事!那涉及到文件修改怎么办呢?
- # f_read = open('小重山','r') #以写读模式打开文件
- # f_write = open('小重山_back','w') #以写读模式打开文件
- # count=0
- # for line in f_read:
- # if count==3:
- # f_write.write('hello,岳飞\n')
- #
- # else:
- # f_write.write(line)
- # another way:
- # if count==3:
- #
- # line='hello,岳飞2\n'
- # f_write.write(line)
- # count+=1
- # #二进制模式
- # f = open('小重山2','wb') #以二进制的形式读文件
- # # f = open('小重山2','wb') #以二进制的形式写文件
- # f.write('hello alvin!'.encode())#b'hello alvin!'就是一个二进制格式的数据,只是为了观看,没有显示成010101的形式
注意:有时会用readlines得到内容列表,再通过索引对相应内容进行修改,最后将列表重新写回到该文件。
这样操作有一个很大的问题,数据若很大,系统内存会受不了;可以通过迭代器来优化这个过程。
with语句
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
- with open('log','r') as f:
- pass
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 后,with 支持同时对多个文件的上下文进行管理,即:
- with open('log1') as obj1, open('log2') as obj2:
- pass
文件处理补充:
阅读目录
一.文件处理流程
- 打开文件,得到文件句柄并赋值给一个变量
- 通过句柄对文件进行操作
- 关闭文件
- 正趣果上果
- Interesting fruit fruit
- 词:郭婞
- 曲:陈粒
- 编曲/混音/和声:燕池
- 萧:吗子
- Words: Guo 婞
- Song: Chen tablets
- Arrange / Mix / Harmony: Yan Chi
- Xiao: Well
- 你佩桃木降妖剑
- 他会一招不要脸
- 哇呀呀呀
- 输在没有钱
- 输在没有钱
- You wear peach down demon sword
- He will shamelessly
- Wow yeah
- Lost in the absence of money
- Lost in the absence of money
- 你愿终老不羡仙
- 谁料温柔终老空了长生殿
- 哎唏唏唏
- 败给好容颜
- 败给好容颜
- You would like to end the old do not envy cents
- Mummy gentle death of the empty palace
- Hey Xi Xi
- Lost to good appearance
- Lost to good appearance
- 人生在世三万天
- 趣果有间 孤独无解
- 苦练含笑半步癫
- 呐我去给你煮碗面
- Life is thirty thousand days
- Fun fruit there is no solution between solitude
- Hard practicing smiling half-step epilepsy
- I'll go and cook your bowl
- 心怀啮雪大志愿
- 被人称作小可怜
- 呜呼呼呼
- 突样未成年
- 突样未成年
- Heart of the snow big volunteer
- Was called a small pitiful
- Alas
- Sudden sample of minor
- Sudden sample of minor
- 本欲歃血定风月
- 乌飞兔走光阴只负尾生约
- 噫嘘嘘嘘
- 真心怕火炼
- 真心也怕火炼
- The desire to set the wind blood months
- Wu Flying Rabbit only time to bear the tail about
- 噫 boo boo
- Really afraid of fire refining
- Really afraid of fire
- 人生在世三万天
- 趣果有间 孤独无解
- 苦练含笑半步癫
- 呐我去给你煮碗面
- Life is thirty thousand days
- Fun fruit there is no solution between solitude
- Hard practicing smiling half-step epilepsy
- I'll go and cook your bowl
- 是非对错二十念
- 十方观遍 庸人恋阙
- 自学睡梦罗汉拳
- 吓 冇知酱紫好危险
- Right and wrong twenty read
- square view over the Yong love Que
- Self - study sleep Lohan boxing
- Scare know that a good risk of Jiang Xi
- 示范文件内容
二.基本操作
2.1 文件操作基本流程初探

- f = open('chenli.txt') #打开文件
- first_line = f.readline()
- print('first line:',first_line) #读一行
- print('我是分隔线'.center(50,'-'))
- data = f.read()# 读取剩下的所有内容,文件大时不要用
- print(data) #打印读取内容
- f.close() #关闭文件

2.2 文件编码
文件保存编码如下
此刻错误的打开方式
- #不指定打开编码,即python解释器默认编码,python2.*为ascii,python3.*为utf-8
f=open('chenli.txt')- f.read()
正确的打开方式
- f=open('chenli.txt',encoding='gbk')
- f.read()
2.3 文件打开模式
- 1 文件句柄 = open('文件路径', '模式')
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
- r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
- w,只写模式【不可读;不存在则创建;存在则清空内容】
- x, 只写模式【不可读;不存在则创建,存在则报错】
- a, 追加模式【可读; 不存在则创建;存在则只追加内容】
"+" 表示可以同时读写某个文件
- r+, 读写【可读,可写】
- w+,写读【可读,可写】
- x+ ,写读【可读,可写】
- a+, 写读【可读,可写】
"b"表示以字节的方式操作
- rb 或 r+b
- wb 或 w+b
- xb 或 w+b
- ab 或 a+b
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码
2.4 文件内置函数flush
flush原理:
- 文件操作是通过软件将文件从硬盘读到内存
- 写入文件的操作也都是存入内存缓冲区buffer(内存速度快于硬盘,如果写入文件的数据都从内存刷到硬盘,内存与硬盘的速度延迟会被无限放大,效率变低,所以要刷到硬盘的数据我们统一往内存的一小块空间即buffer中放,一段时间后操作系统会将buffer中数据一次性刷到硬盘)
- flush即,强制将写入的数据刷到硬盘
滚动条:

- import sys,time
- for i in range(10):
- sys.stdout.write('#')
- sys.stdout.flush()
- time.sleep(0.2)

2.5 文件内光标移动
注意:read(3)代表读取3个字符,其余的文件内光标移动都是以字节为单位如seek,tell,read,truncate
整理中
2.6 open函数详解
1. open()语法
open(file[, mode[, buffering[, encoding[, errors[, newline[, closefd=True]]]]]])
open函数有很多的参数,常用的是file,mode和encoding
file文件位置,需要加引号
mode文件打开模式,见下面3
buffering的可取值有0,1,>1三个,0代表buffer关闭(只适用于二进制模式),1代表line buffer(只适用于文本模式),>1表示初始化的buffer大小;
encoding表示的是返回的数据采用何种编码,一般采用utf8或者gbk;
errors的取值一般有strict,ignore,当取strict的时候,字符编码出现问题的时候,会报错,当取ignore的时候,编码出现问题,程序会忽略而过,继续执行下面的程序。
newline可以取的值有None, \n, \r, ”, ‘\r\n',用于区分换行符,但是这个参数只对文本模式有效;
closefd的取值,是与传入的文件参数有关,默认情况下为True,传入的file参数为文件的文件名,取值为False的时候,file只能是文件描述符,什么是文件描述符,就是一个非负整数,在Unix内核的系统中,打开一个文件,便会返回一个文件描述符。
2. Python中file()与open()区别
两者都能够打开文件,对文件进行操作,也具有相似的用法和参数,但是,这两种文件打开方式有本质的区别,file为文件类,用file()来打开文件,相当于这是在构造文件类,而用open()打开文件,是用python的内建函数来操作,建议使用open
3. 参数mode的基本取值
Character | Meaning |
‘r' | open for reading (default) |
‘w' | open for writing, truncating the file first |
‘a' | open for writing, appending to the end of the file if it exists |
‘b' | binary mode |
‘t' | text mode (default) |
‘+' | open a disk file for updating (reading and writing) |
‘U' | universal newline mode (for backwards compatibility; should not be used in new code) |
r、w、a为打开文件的基本模式,对应着只读、只写、追加模式;
b、t、+、U这四个字符,与以上的文件打开模式组合使用,二进制模式,文本模式,读写模式、通用换行符,根据实际情况组合使用、
常见的mode取值组合

- 1 r或rt 默认模式,文本模式读
- 2 rb 二进制文件
- 3
- 4 w或wt 文本模式写,打开前文件存储被清空
- 5 wb 二进制写,文件存储同样被清空
- 6
- 7 a 追加模式,只能写在文件末尾
- 8 a+ 可读写模式,写只能写在文件末尾
- 9
- 10 w+ 可读写,与a+的区别是要清空文件内容
- 11 r+ 可读写,与a+的区别是可以写到文件任何位置

Python基础7:文件操作的更多相关文章
- python基础篇(文件操作)
Python基础篇(文件操作) 一.初始文件操作 使用python来读写文件是非常简单的操作. 我们使用open()函数来打开一个文件, 获取到文件句柄. 然后通过文件句柄就可以进行各种各样的操作了. ...
- python基础之文件操作
对于文件操作中最简单的操作就是使用print函数将文件输出到屏幕中,但是这种操作并不能是文件保存到磁盘中去,如果下调用该数据还的重新输入等. 而在python中提供了必要的函数和方法进行默认情况下的文 ...
- Day3 Python基础学习——文件操作、函数
一.文件操作 1.对文件操作流程 打开文件,得到文件句柄并赋值给一个变量 通过文件句柄对文件进行操作 关闭文件 #打开文件,读写文件,关闭文件 http://www.cnblogs.com/linha ...
- python基础14_文件操作
文件操作,通常是打开,读,写,追加等.主要涉及 编码 的问题. #!/usr/bin/env python # coding:utf-8 ## open实际上是从OS请求,得到文件句柄 f = ope ...
- 【python基础】文件操作
文件操作目录 一 .文件操作 二 .打开文件的模式 三 .操作文件的方法 四 .文件内光标移动 五. 文件的修改 一.文件操作介绍 计算机系统分为:计算机硬件,操作系统,应用程序三部分. 我们用pyt ...
- python基础4文件操作
在磁盘上读取文件的 功能都是由操作系统来实现的,不允许普通的程序直接操作磁盘,所以读写文件就是请求操作系统打开一个文件对象(通常称为文件描述符),然后,通过操作系统提供的接口从这个文件对象中读取数据( ...
- Python基础 之 文件操作
文件操作 一.路径 文件绝对路径:d:\python.txt 文件相对路径:在IDEA左边的文件夹中 二.编码方式 utf-8 gbk... 三.操作方式 1.只读 r 和 rb 绝对路径的打开操作 ...
- Python基础--基本文件操作
全部的编程语言都一样,学完了一些自带的数据机构后,就要操作文件了. 文件操作才是实战中的王道. 所以,今天就来分享一下Python中关于文件的一些基本操作. open方法 文件模式 这个模式对于写入文 ...
- python基础(10):文件操作
1. 初识文件操作 使⽤python来读写⽂件是非常简单的操作.我们使⽤open()函数来打开⼀个⽂件,获取到⽂ 件句柄,然后通过⽂件句柄就可以进⾏各种各样的操作了,根据打开⽅式的不同能够执⾏的操 作 ...
- Python基础学习——文件操作、函数
一.文件操作 文件操作链接:http://www.cnblogs.com/linhaifeng/articles/5984922.html(更多内容见此链接) 一.对文件操作流程 打开文件,得到文件句 ...
随机推荐
- Linux 通过sendmail 发邮件到外部邮箱
最近在写自动化巡检脚本,想着怎么预警后自动发送邮件报警. 首先下载最新版本mailx-12.4.tar.bz2 # wget http://sourceforge.net/projects/heirl ...
- 《java JDK7 学习笔记》之对象封装
1.构造函数实现对象初始化流程的封装.方法封装了操作对象的流程.java中还可以使用private封装对象私有数据成员.封装的目的主要就是隐藏对象细节,将对象当做黑箱子进行操作. 2.在java命名规 ...
- W3School-CSS 轮廓(Outline)实例
CSS 轮廓(Outline)实例 CSS 实例 CSS 背景实例 CSS 文本实例 CSS 字体(font)实例 CSS 边框(border)实例 CSS 外边距 (margin) 实例 CSS 内 ...
- 分布式搜索引擎ElasticSearch+Kibana (Marvel插件安装详解)
在安装插件的过程中,尤其是安装Marvel插件遇到了很多问题,要下载license.Marvel-agent,又要下载安装Kibana 版本需求 Java 7 or later Elasticsear ...
- 3-1 Linux文件管理类命令详解
根据马哥Linux初级 03-01整理 1. 目录管理 ls cd pwd mkdir rmdir tree 2. 文件管理 touch stat file rm cp mv nano 3. 日期时间 ...
- log4j 不同模块输出到不同的文件
1.实现目标 不同业务的日志信息需要打印到不同的文件中,每天或者每个小时生成一个文件.如,注册的信息打印到register.log,每天凌晨生成一个register-年月日.log文件, 登录信息的日 ...
- Java关键字 ClassName.this(类名.this)的理解
关键字this用于指代当前的对象.因此,类内部可以使用this作为前缀引用实例成员: this()代表了调用另一个构造函数,至于调用哪个构造函数根据参数表确定.this()调用只 能出现在构造函数的第 ...
- java1.8函数式接口
package com.wzy.t1; @FunctionalInterface//此注解用来声明此接口为函数式接口 public interface People { /** * 1.函数式接口只能 ...
- python_爬虫一之爬取糗事百科上的段子
目标 抓取糗事百科上的段子 实现每按一次回车显示一个段子 输入想要看的页数,按 'Q' 或者 'q' 退出 实现思路 目标网址:糗事百科 使用requests抓取页面 requests官方教程 使用 ...
- C#.NET 大型企业信息化系统集成快速开发平台 4.2 版本 - 角色权限的配置页面改进优化
往往开发的人不是维护的人,开发的单位不是维护的单位.信息的畅通沟通交流很多时候会有打折.扭曲.甚至是容易得到歪解.配置错业务操作权限.为了防止发生没必要的麻烦,甚至是发生重大错误,我们的软件需要不断换 ...