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") 说明: 第一个参数是文件名称,包括路径: 第二个参数是打开的模式 ...
随机推荐
- TextView右上角显示小红点,小红点根据TextView的长度移动,小红点被TextView挤出去不显示的问题;
大概就是图片这个样,这个功能很常见,本来我以为很简单,谁知道真的很简单: 遇到点小问题,记录一下,哈哈: 小红点的Drawable: <?xml version="1.0" ...
- 由js文件中引入另外的js文件想到的
1. html中,使用<script src="../static/js/xxx.js"></script>引入js文件. 2. 在js文件中,引入js ...
- dns 域名地址
Public DNS+ 是属于 腾讯云旗下的公共 DNS 服务.拥有 80 多条国内线路和 4 条海外线路,有 BGP Anycast 技术,也是国内首家支持谷歌 ECS (edns-client-s ...
- element-ui 带单选框的表格
效果:不只是带单选框,点击当前行单选框选中状态网上查了一些发现很多都是只能点击当前radio选中当前行,配合element-ui的单选table时发现两个的选择状态是不一致的,所以调整了一下效果 提供 ...
- [Unity插件]Lua行为树(十三):装饰节点完善
之前介绍了组合节点中三大常用的节点:BTSequence.BTSelector和BTParallel,一般来说,这三种就够用了,可以满足很多的需求. 接下来可以完善一下装饰节点,增加几种新的节点. 1 ...
- 【Servlet】监听器入门
- 网络表示学习Network Representation Learning/Embedding
网络表示学习相关资料 网络表示学习(network representation learning,NRL),也被称为图嵌入方法(graph embedding method,GEM)是这两年兴起的工 ...
- mysqld服务启动失败, Failed to restart mysqld.service: Unit not found.
-bash-4.2# service mysqld restart Redirecting to /bin/systemctl restart mysqld.serviceFailed to rest ...
- <转载>apache 配置 http://www.blogjava.net/bukebushuo/articles/229103.html
基于 NCSA 服务器的配置文件 由 Rob McCool 编写,龙子翻译 Apache服务器主配置文件. 包括服务器指令的目录设置. 详见 <URL:http://www.apache.org ...
- 水仙花在python3在pycharm的实现
---恢复内容开始--- #方法一:#-*- coding: utf-8-*-while True: num = input("请输入一个三位数") num = int(num) ...