Python的文件操作
文件操作,顾名思义,就是对磁盘上已经存在的文件进行各种操作,文本文件就是读和写。
1. 文件的操作流程
(1)打开文件,得到文件句柄并赋值给一个变量
(2)通过句柄对文件进行操作
(3)关闭文件
现有文件
昔闻洞庭水,今上岳阳楼。
吴楚东南坼,乾坤日夜浮。
亲朋无一字,老病有孤舟。
戎马关山北,凭轩涕泗流。
2. 文件的打开模式
打开文件的模式:
三种基本模式:
1. r,只读模式(默认)
2. w,只写模式。(不可读,不存在文件则创建,存在则删除内容)
3. a,追加模式。(不存在文件则创建,存在则在文件末尾追加内容)
“+” 表示可以同时读写某个文件
4.r+,可读写。(读文件从文件起始位置,写文件则跳转到文件末尾添加)
5.w+,可写读。(文件不存在就创建文件,文件存在则清空文件,之后可写可读)
6.a+,可读写,读和写都从文件末尾开始。
“U” 表示在读取时,可以将\r\n\r\n自动转换成\n(与r或r+模式同使用)
7.rU
8.r+U
“b” 表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需要标注)
9. rb
10.wb
11.ab
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 操作方法介绍
具体操作
open()打开文件
close()关闭文件 f = open('登岳阳楼','r')
print(f.read()) #读取所有
>>>
昔闻洞庭水,今上岳阳楼。
吴楚东南坼,乾坤日夜浮。
亲朋无一字,老病有孤舟。
戎马关山北,凭轩涕泗流 print(f.read(5)) #读取5个字
>>>
昔闻洞庭水 print(f.readline()) #读取一行
print(f.readline()) #继续执行,读取下一行
>>>
昔闻洞庭水,今上岳阳楼。 吴楚东南坼,乾坤日夜浮。 print(f.readlines()) #以列表形式读出文件
>>>
['昔闻洞庭水,今上岳阳楼。\n', '吴楚东南坼,乾坤日夜浮。\n', '亲朋无一字,老病有孤舟。\n', '戎马关山北,凭轩涕泗流。']
for i in f.readlines():
print(i)
>>>
昔闻洞庭水,今上岳阳楼。 吴楚东南坼,乾坤日夜浮。 亲朋无一字,老病有孤舟。 戎马关山北,凭轩涕泗流。
还可以用:(建议这种方法)
for i in f:
print(i) print(f.tell()) #指出光标所在位置r模式打开文件默认光标在初始位置0
>>>
0 f = open('登岳阳楼','r',encoding='utf-8')
print(f.tell())
f.seek(5)
print(f.tell())
>>>
0
5
f.seek() 用于调整光标位置类似于下载时的断线重连 f = open('登岳阳楼','w',encoding='utf-8')
f.write('hello world')
>>>
hello world
#用w模式打开文件将会清除文件所有内容,再添加write()中的内容 f.flush() #写文件时,写的内容不会直接写到文件中,而是保存在内存里,等文件close后才写入文件,flush()方法就是将内存中的内容立刻写入文件。可用于进度条 f = open('登岳阳楼','w',encoding='utf-8')
f.write('hello world')
f.truncate(4) #截断内容
>>>
hell
with语句
为了防止我们在对文件操作后忘记close()文件,可以通过with语句对文件操作,
with open('登岳阳楼','r',encoding='utf-8') as f:
print(f.read())
>>>
昔闻洞庭水,今上岳阳楼。
吴楚东南坼,乾坤日夜浮。
亲朋无一字,老病有孤舟。
戎马关山北,凭轩涕泗流。
当with语句执行完毕,文件就默认关闭了。
Python的文件操作的更多相关文章
- Python :open文件操作,配合read()使用!
python:open/文件操作 open/文件操作f=open('/tmp/hello','w') #open(路径+文件名,读写模式) 如何打开文件 handle=open(file_name,a ...
- Python 常见文件操作的函数示例(转)
转自:http://www.cnblogs.com/txw1958/archive/2012/03/08/2385540.html # -*-coding:utf8 -*- ''''' Python常 ...
- 孤荷凌寒自学python第三十五天python的文件操作之针对文件操作的os模块的相关内容
孤荷凌寒自学python第三十五天python的文件操作之针对文件操作的os模块的相关内容 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 一.打开文件后,要务必记得关闭,所以一般的写法应当 ...
- 孤荷凌寒自学python第三十三天python的文件操作初识
孤荷凌寒自学python第三十三天python的文件操作初识 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 今天开始自学python的普通 文件操作部分的内容. 一.python的文件打开 ...
- python中文件操作的六种模式及对文件某一行进行修改的方法
一.python中文件操作的六种模式分为:r,w,a,r+,w+,a+ r叫做只读模式,只可以读取,不可以写入 w叫做写入模式,只可以写入,不可以读取 a叫做追加写入模式,只可以在末尾追加内容,不可以 ...
- python中文件操作的其他方法
前面介绍过Python中文件操作的一般方法,包括打开,写入,关闭.本文中介绍下python中关于文件操作的其他比较常用的一些方法. 首先创建一个文件poems: p=open('poems','r', ...
- Python常见文件操作的函数示例
# -*-coding:utf8 -*- ''''' Python常见文件操作示例 os.path 模块中的路径名访问函数 分隔 basename() 去掉目录路径, 返回文件名 dirname() ...
- python的文件操作及简单的用例
一.python的文件操作介绍 1.文件操作函数介绍 open() 打开一个文件 语法:open(file, mode='r', buffering=-1, encoding=None, errors ...
- python基本文件操作
python文件操作 python的文件操作相对于java复杂的IO流简单了好多,只要关心文件的读和写就行了 基本的文件操作 要注意的是,当不存在某路径的文件时,w,a模式会自动新建此文件夹,当读模式 ...
- [转]python file文件操作--内置对象open
python file文件操作--内置对象open 说明: 1. 函数功能打开一个文件,返回一个文件读写对象,然后可以对文件进行相应读写操作. 2. file参数表示的需要打开文件的相对路径(当前 ...
随机推荐
- android 视频录制 混淆打包 之native层 异常的解决
原文地址:http://www.cnblogs.com/linguanh/ (滑至文章末,直接看解决方法) 问题起因: 前5天,因为项目里面有个类似 仿微信 视频录制的功能, 先是上网找了个 开 ...
- [Servlet] 初识Servlet
什么是Servlet? 定义 Servlet的全称是 Server Applet,顾名思义,就是用 Java 编写的服务器端程序. Servlet 是一个 Java Web开发标准,狭义的Servle ...
- LCS记录
如题:求两个序列的最长公共序列.(如:"ABCBDAB"与"BCDB"最长公共序列为"BCDB")代码如下: #define MAX_SIZ ...
- 前端开发:面向对象与javascript中的面向对象实现(一)
前端开发:面向对象与javascript中的面向对象实现(一) 前言: 人生在世,这找不到对象是万万不行的.咱们生活中,找不到对象要挨骂,代码里也一样.朋友问我说:“嘿,在干嘛呢......”,我:“ ...
- H5天气查询demo(二)
最近刚好有空,学长帮忙让做个毕设,于是我提到了那个基于H5地理位置实现天气查询的方法,学长听了也觉得不错,于是就这个主题,扩展了一下,做了一个航班管理查询系统,为上次博客中提到的利用H5 api中的经 ...
- C#递归解决汉诺塔问题(Hanoi)
using System;using System.Collections.Generic;using System.Linq;using System.Text; namespace MyExamp ...
- Python时间戳和日期的相互转换
Python时间戳和日期的相互转换 (2014-03-17 11:24:35) 转载▼ 分类: Python 当前时间戳:time.time() 当前日期:time.ctime() 1.Pytho ...
- 手游聚合SDK开发之远程开关---渠道登入白名单
白名单有啥好说的呢?无非就是筛选登入,大家第一眼看到就是这个印象,白名单也是有文章的,弄的时机不同会给你带来很不错的收益,注意是收益.还是举例来说,游戏上线前渠道都会做一个预下载,一般提前1-2天,这 ...
- HTML5 数据集属性dataset
有时候在HTML元素上绑定一些额外信息,特别是JS选取操作这些元素时特别有帮助.通常我们会使用getAttribute()和setAttribute()来读和写非标题属性的值.但为此付出的代价是文档将 ...
- Mysql性能优化一
下一篇:Mysql性能优化二 mysql的性能优化无法一蹴而就,必须一步一步慢慢来,从各个方面进行优化,最终性能就会有大的提升. Mysql数据库的优化技术 对mysql优化是一个综合性的技术,主要包 ...