韦大仙--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叫做追加写入模式,只可以在末尾追加内容,不可以 ...
随机推荐
- 记录一次Git问题及其解决方案
错误信息:fatal: refusing to merge unrelated histories 错误产生背景:我将原先测试的项目本地删除后提交,然后将新的项目按照git的提交步骤进行提交,在最后一 ...
- C51 单片机的中断号以及中断向量
1.外部中断0. 1:分别由引脚/INT0./INT1的电平信号引起. 2.定时/计数器0.1:分别由T0. T1的溢出引起. 3.串行口发送.接收:发送完一个字节或接收到一个字节引起. 上述共5个中 ...
- Oracle分区表删除分区引发错误ORA-01502: 索引或这类索引的分区处于不可用状态
(一)问题: 最近在做Oracle数据清理,在对分区表进行数据清理时,采用的方法是drop partition,删除的过程中,没有遇到任何问题,大概过了10分钟,开发人员反馈部分分区表上的业务失败.具 ...
- 免安装版MySQL8数据库的安装
[环境准备] PC版本:Windows10企业版.64位操作系统 数据库:MySQL8.0.12-win64.zip免安装版 [彻底卸载已安装的MySQL数据库] 由于系统中MySQL数据库的卸载不彻 ...
- Spring的入门学习笔记 (AOP概念及操作+AspectJ)
AOP概念 1.aop:面向切面(方面)编程,扩展功能不通过源代码实现 2.采用横向抽取机制,取代了传统的纵向继承重复代码 AOP原理 假设现有 public class User{ //添加用户方法 ...
- 关于mybatis编写sql问题.
最近呢楼主回到长沙进行面试:被问了一个这样的问题,在mybatis中怎么进行模糊查询,望各位大佬在下方进行评论,好让我这菜鸡多学习一些.
- JSON字符串与JS对象格式转换
JSON通常用于服务器向客户端传送数据,传回来的JSON数据是字符串的形式,所以要转变为JS对象形式才方便我们使用. JSON字符串转变为JS对象:JSON.parse( ); JS对象转变为JSON ...
- angular常用属性大全
Angular元素属性大全 addClass()-为每个匹配的元素添加指定的样式类名 after()-在匹配元素集合中的每个元素后面插入参数所指定的内容,作为其兄弟节点 append()-在每个匹配元 ...
- redis整合Spring之序列化对象与反序列化
写在最前面 1.Spring必须是4.2.6及以上版本才支持redis 2.jar包版本建议统一 需要准备jar包 1.aopalliance-1.0.jar 2.spring-data-common ...
- PHP 通过命令异步执行PHP程序
通过PHP执行系统命令调用PHP执行程序,让进程挂起到后台执行,不影响用户页面交互. 控制器调用命令,不用等待,后台创建一个进程执行程序. system(“nohup php command.php ...