Python读写文件基础.py
基本函数
定义
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的更多相关文章
- [Python]读写文件方法
http://www.cnblogs.com/lovebread/archive/2009/12/24/1631108.html [Python]读写文件方法 http://www.cnblogs.c ...
- Python 读写文件的正确方式
当你用 Python 写程序时,不论是简单的脚本,还是复杂的大型项目,其中最常见的操作就是读写文件.不管是简单的文本文件.繁杂的日志文件,还是分析图片等媒体文件中的字节数据,都需要用到 Python ...
- Python读写文件
Python读写文件1.open使用open打开文件后一定要记得调用文件对象的close()方法.比如可以用try/finally语句来确保最后能关闭文件. file_object = open('t ...
- Python读写文件实际操作的五大步骤
Python读写文件在计算机语言中被广泛的应用,如果你想了解其应用的程序,以下的文章会给你详细的介绍相关内容,会你在以后的学习的过程中有所帮助,下面我们就详细介绍其应用程序. 一.打开文件 Pytho ...
- python的re模块一些方法 && Tkinter图形界面设计 && 终止python运行函数 && python读写文件 && python一旦给字符串赋值就不能单独改变某个字符,除非重新给变量赋值
Tkinter图形界面设计见:https://www.cnblogs.com/pywjh/p/9527828.html#radiobutton 终止python运行函数: 采用sys.exit(0)正 ...
- python 读写文件和设置文件的字符编码
一. python打开文件代码如下: f = open("d:\test.txt", "w") 说明:第一个参数是文件名称,包括路径:第二个参数是打开的模式mo ...
- Python学习入门基础教程(learning Python)--5.2 Python读文件基础
上节简单的说明了一下Pyhon下的文件读写基本流程,从本节开始,我们做几个小例子来具体展示一下Python下的文件操作,本节主要是详细讲述Python的文件读操作. 下面举一个例子,例子的功能是读取当 ...
- 从用python自动生成.h的头文件集合和类声明集合到用python读写文件
最近在用python自动生成c++的类.因为这些类会根据需求不同产生不同的类,所以需要用python自动生成.由于会产生大量的类,而且这些类是变化的.所以如果是在某个.h中要用include来加载这些 ...
- 【Python开发】python读写文件,和设置文件的字符编码比如utf-8
一. python打开文件代码如下: f = open("d:\test.txt", "w") 说明: 第一个参数是文件名称,包括路径: 第二个参数是打开的模式 ...
随机推荐
- HBase分布式集群部署与设计
先是把cdh版本的hbase上传上来 把安装吧的权限设置一下 解压 把没用的东西干掉 hbase的官网 配置文件 到hbase-site.xml 下面我不基于HA配置了 把hbase分发到其他两个节点 ...
- hive使用map字段
create table role_bigtable(table_name string, record_date string, server_id string, map_col map<s ...
- vue2.0 父子组件数据传递prop
vue的一个核心概念就是组件,而组件实例的作用域是孤立的,所以组件之间是不能直接引用其他组件的数据的.极端点举例来说,就是可以在同一个项目中,每一个组件内都可以定义相同名称的数据. data () { ...
- linux 下的常用操作命令
一,Linux的介绍 略. 二,文件类的常用命令 三,权限类的常用命令
- glob获取指定目录下的东西+更改工作目录
一:不更改工作目录 import glob path = 'image/imgs/*.jpg' # 正则匹配 指定路径 file_path = glob.glob(path) # 即可获取所有jpg的 ...
- Unity3D的断点调试功能
断点调试功能可谓是程序员必备的功能了.Unity3D支持编写js和c#脚本,但很多人可能不知道,其实Unity3D也能对程序进行断点调 试的.不过这个断点调试功能只限于使用Unity3D自带的Mono ...
- FreeMarker之FTL指令
assign指令 此指令用于在页面上定义一个变量 (1)定义简单类型: <#assign linkman="周先生"> 联系人:${linkman} (2)定义对象类型 ...
- <spark> hadoop/spark 集群搭建
参考的这3个文档,虽然搭建花了挺长时间也遇到挺多问题,但是这3个文档对我的帮助确实挺大,如果有兴趣的或者有需要的可以参考以下文档. http://blog.csdn.net/wy250229163/a ...
- 18.Mysql搜索引擎及其区别
这是面试中的问题:当时也是没有直接回答出来,还是因为基础知识不扎实. 一般Mysql常用的搜索引擎有:ISAM.MylSAM.HEAP.InnoDB.Berkley(BDB) ISAM:执行读取操作的 ...
- 《算法》第二章部分程序 part 2
▶ 书中第二章部分程序,加上自己补充的代码,包括若干种归并排序,以及利用归并排序计算数组逆序数 ● 归并排序 package package01; import java.util.Comparato ...