基本函数

定义

python内置了open()函数来操作文件,open()函数的定义为:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.

file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.)

mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), 'x' for exclusive creation and 'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are:

操作模式

Character Meaning

'r' open for reading (default)

'w' open for writing, truncating the file first

'x' open for exclusive creation, failing if the file already exists

'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 newlines mode (deprecated)

读操作

直接读取

要注意在使用完后需要close

#读取文件
def readDemo1(self):
#以只读模式打开文件,如果打开失败有error输出
try:
f = open('D:\\readfiledemo.txt', 'r')
print(f.read())
#要用finally来关闭文件!
finally:
if f:
f.close()

更简洁的读取

使用with的方式可以避免忘记close

def readDemo2(self):
try:
#使用with的方式可以不用主动close
with open('D:\\readfiledemo.txt', 'r') as f:
print(f.read())
except:
pass

按照行读取

上面的操作方式如果是文件太大那么直接程序就异常或者崩溃,并且通常使用时候按照行读取也更为实用

def readDemo3(self):
try:
with open('D:\\readfiledemo.txt', 'r') as f:
#按照行读取
for line in f.readlines():
#去除行尾的\n
print(line.strip())
except:
pass

读取二进制文件:

#二进制的方式读取,例如图片音乐文件等
def readDemo4(self):
try:
#一次性的读取,文件太大就会崩溃了!!!
with open('D:\\error.bak', 'rb') as f:
print(f.read())
except:
pass

以指定编码字符集来读取

通常很多文件有编码字符集的要求,如果不使用指定格式那么就会有乱码。如果不需要提示异常那么直接配置为忽略模式即可

#指定字符集的方式读取,并且忽略错误
def readDemo5(self):
try:
with open('D:\\example.log', 'r', encoding='utf-8', errors='ignore') as f:
#按照行读取
for line in f.readlines():
#去除行尾的\n
print(line.strip())
except:
pass

写操作

写操作和读操作基本上一致,需要注意的有两点:

  • 如果使用的是非with的方式,那么要注意在close操作中才会写入文件,否则是没有提交的
  • 写的时候要注意模式是追加还是覆盖
def wirteDemo1(self):
try:
#w:覆盖式写入
#a:追加式写入
with open('D:\\example.log', 'w', encoding='utf-8', errors='ignore') as f:
f.write('this a 例子')
f.write('\rthis a 例子 追加')
except:
pass

内存读写

内存读写通过StringIO和BytesIO来操作,前者操作字符流,后者操作二进制流。使用和open类似

Python读写文件基础.py的更多相关文章

  1. [Python]读写文件方法

    http://www.cnblogs.com/lovebread/archive/2009/12/24/1631108.html [Python]读写文件方法 http://www.cnblogs.c ...

  2. Python 读写文件的正确方式

    当你用 Python 写程序时,不论是简单的脚本,还是复杂的大型项目,其中最常见的操作就是读写文件.不管是简单的文本文件.繁杂的日志文件,还是分析图片等媒体文件中的字节数据,都需要用到 Python ...

  3. Python读写文件

    Python读写文件1.open使用open打开文件后一定要记得调用文件对象的close()方法.比如可以用try/finally语句来确保最后能关闭文件. file_object = open('t ...

  4. Python读写文件实际操作的五大步骤

    Python读写文件在计算机语言中被广泛的应用,如果你想了解其应用的程序,以下的文章会给你详细的介绍相关内容,会你在以后的学习的过程中有所帮助,下面我们就详细介绍其应用程序. 一.打开文件 Pytho ...

  5. python的re模块一些方法 && Tkinter图形界面设计 && 终止python运行函数 && python读写文件 && python一旦给字符串赋值就不能单独改变某个字符,除非重新给变量赋值

    Tkinter图形界面设计见:https://www.cnblogs.com/pywjh/p/9527828.html#radiobutton 终止python运行函数: 采用sys.exit(0)正 ...

  6. python 读写文件和设置文件的字符编码

    一. python打开文件代码如下: f = open("d:\test.txt", "w") 说明:第一个参数是文件名称,包括路径:第二个参数是打开的模式mo ...

  7. Python学习入门基础教程(learning Python)--5.2 Python读文件基础

    上节简单的说明了一下Pyhon下的文件读写基本流程,从本节开始,我们做几个小例子来具体展示一下Python下的文件操作,本节主要是详细讲述Python的文件读操作. 下面举一个例子,例子的功能是读取当 ...

  8. 从用python自动生成.h的头文件集合和类声明集合到用python读写文件

    最近在用python自动生成c++的类.因为这些类会根据需求不同产生不同的类,所以需要用python自动生成.由于会产生大量的类,而且这些类是变化的.所以如果是在某个.h中要用include来加载这些 ...

  9. 【Python开发】python读写文件,和设置文件的字符编码比如utf-8

    一. python打开文件代码如下: f = open("d:\test.txt", "w") 说明: 第一个参数是文件名称,包括路径: 第二个参数是打开的模式 ...

随机推荐

  1. C# DataGridView导出Excel

    using Microsoft.Office.Interop.Excel;                using Excel=Microsoft.Office.Interop.Excel; //这 ...

  2. Html5——音频标签使用

    Ogg 文件,适用于Firefox.Opera 以及 Chrome 浏览器. 要确保适用于 Safari 浏览器,音频文件必须是 MP3 或 Wav 类型. audio 元素允许多个 source 元 ...

  3. celipse关联hadoop源码

    可以在这里下载hadoop的源码包 https://mirrors.tuna.tsinghua.edu.cn/apache/hadoop/common/ 我自己下载的是hadoop2.6.0的源码包 ...

  4. tp5 post接到的json被转义怎么解决???

    $data =input('post.');//用户唯一标识$goods = $data['goods']; $shopcuxiao=$data['shopcuxiao']; $goods=htmls ...

  5. oracle insert 返回ID

    create or replace procedure getid(v_id out number)as  v_sql varchar2(500); begin v_sql:='insert into ...

  6. linux 之 source命令:

    source命令: source命令也称为“点命令”,也就是一个点符号(.).source命令通常用于重新执行刚修改的初始化文件,使之立即生效,而不必注销并重新登录. 用法: source filen ...

  7. C# 反射常见用法

    定义: 反射是.NET中的重要机制,通过反射,可以在运行时获得程序或程序集中每一个类型(包括类.结构.委托.接口和枚举等)的成员和成员的信息.有了反射,即可对每一个类型了如指掌.另外我还可以直接创建对 ...

  8. (1)Linux操作系统的安装

    1.安装Vmware Workstation 如何判断Vmware是否安装成功? 我的电脑控制面板 --> 网络和Internet --> 查看网络状态和任务 --> 更改适配器设置 ...

  9. MySQL配置文件以及服务的开启关闭重启

    linux系统中,配置文件路径一般为/etc/my.cnf [root@host ~]# mysql --help|grep my.cnf                       order of ...

  10. <基础> PHP 数据类型

    PHP三大数据类型 标量 字符串 单引号:不能解析变量  效率高 双引号 :可以解析变量   效率稍微低一些 heredoc : 大文本 整形 浮点 不能用于比较运算 布尔 复合 数组 超全局数组  ...