韦大仙--python对文件操作
文件操作:
对文件操作流程
- 打开文件,得到文件句柄并赋值给一个变量
- 通过句柄对文件进行操作
- 关闭文件
现有文件如下
Somehow, it seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种
Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
就如舌尖上的雨露
I teased at life as if it were a foolish game
我戏弄生命 视其为愚蠢的游戏
The way the evening breeze
就如夜晚的微风
May tease the candle flame
逗弄蜡烛的火苗
The thousand dreams I dreamed
我曾千万次梦见
The splendid things I planned
那些我计划的绚丽蓝图
I always built to last on weak and shifting sand
但我总是将之建筑在易逝的流沙上
I lived by night and shunned the naked light of day
我夜夜笙歌 逃避白昼赤裸的阳光
And only now I see how the time ran away
基本操作
f
=
open
(
'lyrics'
)
#打开文件
first_line
=
f.readline()
print
(
'first line:'
,first_line)
#读一行
print
(
'我是分隔线'
.center(
50
,
'-'
))
data
=
f.read()
# 读取剩下的所有内容,文件大时不要用
print
(data)
#打印文件
f.close()
#关闭文件
打开文件的模式有:
- r,只读模式(默认)。
- w,只写模式。【不可读;不存在则创建;存在则删除内容;】
- a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
- r+,可读写文件。【可读;可写;可追加】
- w+,写读
- a+,同a
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
- rU
- r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
- rb
- wb
- ab
其它语法
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 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 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 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 readinto(self): # real signature unknown; restored from __doc__
""" Same as RawIOBase.readinto(). """
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 seekable(self, *args, **kwargs): # real signature unknown
""" True if file supports random-access. """
pass def tell(self, *args, **kwargs): # real signature unknown
"""
Current file position. Can raise OSError for non seekable files.
"""
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 writable(self, *args, **kwargs): # real signature unknown
""" True if file was opened in a write mode. """
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
with语句
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
with
open
(
'log'
,
'r'
) as f:
...
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
with
open
(
'log1'
) as obj1,
open
(
'log2'
) as obj2:
pass
韦大仙--python对文件操作的更多相关文章
- 韦大仙--python对文件操作 2--写入与修改
请大家看一段代码: yesterday2是我之前上个帖子创建的文件,为了方便大家看清我把本来的代码复制到下面: coding=utf-8 f=open("yesterday2",& ...
- 孤荷凌寒自学python第三十五天python的文件操作之针对文件操作的os模块的相关内容
孤荷凌寒自学python第三十五天python的文件操作之针对文件操作的os模块的相关内容 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 一.打开文件后,要务必记得关闭,所以一般的写法应当 ...
- 孤荷凌寒自学python第三十三天python的文件操作初识
孤荷凌寒自学python第三十三天python的文件操作初识 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 今天开始自学python的普通 文件操作部分的内容. 一.python的文件打开 ...
- python的文件操作及简单的用例
一.python的文件操作介绍 1.文件操作函数介绍 open() 打开一个文件 语法:open(file, mode='r', buffering=-1, encoding=None, errors ...
- python系列——文件操作的代码
import numpy as np import os,sys #获取当前文件夹,并根据文件名 def path(fileName): p=sys.path[0]+'\\'+fileName ret ...
- 员工管理系统+字符编码+Python代码文件操作
员工管理系统+字符编码+Python代码文件操作 1.员工管理系统 1.1 debug 代码调试 1.先使用鼠标左键在需要调试的代码左边点击一下(会出现一个红点)2.之后右键点击debug运行代码 ...
- 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中文件操作的六种模式分为:r,w,a,r+,w+,a+ r叫做只读模式,只可以读取,不可以写入 w叫做写入模式,只可以写入,不可以读取 a叫做追加写入模式,只可以在末尾追加内容,不可以 ...
随机推荐
- JAVA正则表达式判断元音
/* * 判断字符串”qaq”中间的字符是否是元音 * * aeiou * AEIOU * */ (1)正则表达式 (2) (3)
- 使用 input[type=file]上传文件
var $file = $('#file'); $('#btn').click(function() { var data = new FormData(); data.append('file', ...
- iOS:SQL
iOS虽然也有SQL,不过用得少(至少我目前是这样).大数据直接丢给后台,小的用Plist足矣. 再退一步,有FMDB,原生的也用得少了. 下面是之前学SQL时候的笔记. 1.创建 1-1).打开: ...
- php-预定义
php预定义异常 Exception是所有异常的基类 属性 message:异常消息内容 code:异常代码 file:抛出异常的文件名 line:抛出异常在该文件的行号 ErrorException ...
- js 变速动画函数
//获取任意一个元素的任意一个属性的当前的值---当前属性的位置值 function getStyle(element, attr) { return window.getComputedStyle ...
- JQuery的焦点事件focus() 与按键事件keydown() 及js判断当前页面是否为顶级页面 子页面刷新将顶级页面刷新 window.top.location
相关代码如下,使用看注解 <script type="text/javascript"> if(window.self != window.top){ window.t ...
- 原生js实现简单轮播的淡入淡出效果
实现这种淡入淡出的轮播关键在于css的一种设置 首先它不能像传统的轮播显示隐藏 或者左右浮动 他应该让其固定定位使其重叠在一起 达到这种效果 然后设置c3动画属性 transition:1s; ...
- 《MySQL必知必会》--使用cmd登陆数据库
数据库:保存有组织的数据的容器(通常是一个文件或一组文件). 表:某种特定类型数据的结构化清单. 模式:关于数据库和表的布局及特性的信息. 列:表中的一个字段.所有表都是由一个或多个列组成的. 数据类 ...
- GitLab 基本操作
登录 在浏览其中输入http://192.168.3.11:8888 如图1登录界面. 图1 注:第一次新增用户,会发送修改密码链接到用户的邮箱中,用户会收到如图2邮件. 图2 2. 修改密码 点 ...
- 第8天 Java基础语法
第8天 Java基础语法 今日内容介绍 Eclipse开发工具 超市库存管理系统 Eclipse开发工具 Eclipse是功能强大Java集成开发工具.它可以极大地提升我们的开发效率.可以自动编译,检 ...