小白的Python之路 day2 文件操作
文件操作
对文件操作流程
- 打开文件,得到文件句柄并赋值给一个变量
- 通过句柄对文件进行操作
- 关闭文件
现有文件如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
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 事到如今我才看清岁月是如何匆匆流逝 Yesterday when I was young 昨日当我年少轻狂 So many lovely songs were waiting to be sung 有那么多甜美的曲儿等我歌唱 So many wild pleasures lay in store for me 有那么多肆意的快乐等我享受 And so much pain my eyes refused to see 还有那么多痛苦 我的双眼却视而不见 I ran so fast that time and youth at last ran out 我飞快地奔走 最终时光与青春消逝殆尽 I never stopped to think what life was all about 我从未停下脚步去思考生命的意义 And every conversation that I can now recall 如今回想起的所有对话 Concerned itself with me and nothing else at all 除了和我相关的 什么都记不得了 The game of love I played with arrogance and pride 我用自负和傲慢玩着爱情的游戏 And every flame I lit too quickly, quickly died 所有我点燃的火焰都熄灭得太快 The friends I made all somehow seemed to slip away 所有我交的朋友似乎都不知不觉地离开了 And only now I'm left alone to end the play, yeah 只剩我一个人在台上来结束这场闹剧 Oh, yesterday when I was young 噢 昨日当我年少轻狂 So many, many songs were waiting to be sung 有那么那么多甜美的曲儿等我歌唱 So many wild pleasures lay in store for me 有那么多肆意的快乐等我享受 And so much pain my eyes refused to see 还有那么多痛苦 我的双眼却视而不见 There are so many songs in me that won't be sung 我有太多歌曲永远不会被唱起 I feel the bitter taste of tears upon my tongue 我尝到了舌尖泪水的苦涩滋味 The time has come for me to pay for yesterday 终于到了付出代价的时间 为了昨日 When I was young 当我年少轻狂 |
基本操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
f = open ( 'yesterday',encoding = 'utf-8' ) #打开文件 #low loop
for index,line in enumerate(f.readlines()): if index == 9:
print('------------------------')
continue
print(line.strip())
#high bige
for line in f:
if count == 9:
print('-----------------------')
count += 1
continue
print(line)
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 字符串 转换 encode
- 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
import sys
f = open("yesterday2","r",encoding="utf-8")
f_new = open("yesterday2.bak","w",encoding="utf-8")
find_str = sys.argv[1]
replace_str = sys.argv[2]
for line in f:
if find_str in line:
line = line.replace(find_str,replace_str)
f_new.write(line)
f.close()
f_new.close()
with语句
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
1
2
3
|
with open ( 'log' , 'r' ) as f: ... |
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
1
2
|
with open ( 'log1' ) as obj1, open ( 'log2' ) as obj2: pass |
小白的Python之路 day2 文件操作的更多相关文章
- 小白的Python之路 day2 字符串操作 , 字典操作
1. 字符串操作 特性:不可修改 name.capitalize() 首字母大写 name.casefold() 大写全部变小写 name.center(50,"-") 输出 '- ...
- python之路(五)-文件操作
文件操作无非两个,即:读.写 python 2.x: 文件句柄 = file('文件路径', '模式') python3.x: 文件句柄 = open('文件路径', '模式') 打开文件的模式有: ...
- python之路---08 文件操作
二十六. 文件 f = open(文件路径,mode = '模式',encoding = '编码格式') 1.基础 ① 读写时,主要看光标的位置 ②操作完成要写 f.close( ) f.f ...
- Python之路 day2 文件基础操作
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author:ersa ''' #f,文件句柄;模式 a : append 追加文件内容 f = open( ...
- 小白的Python之路 day2 列表、元组操作
1. 列表.元组操作 列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储.修改等操作 定义列表 1 names = ['Tom','Jack','Qian'] 通过下标访问列表中 ...
- 小白学习Python之路---py文件转换成exe可执行文件
一.背景 今天闲着无事,写了一个小小的Python脚本程序,然后给同学炫耀的时候,发现每次都得拉着其他人过来看着自己的电脑屏幕,感觉不是很爽,然后我想着网上肯定有关于Python脚本转换成可执行文件的 ...
- 小白的Python之路 day2 字符编码和转码
字符编码和转码 详细文章: http://www.cnblogs.com/yuanchenqi/articles/5956943.html http://www.diveintopython3.net ...
- python成长之路五-文件操作
1,文件操作 f = open("D:\种子.txt",encoding="utf-8",mode="r") # 打开一个种子.txt文件, ...
- Python学习之路4 - 文件操作&编码转换
文件操作 文件操作大概分三步: 把文件打开. 操作文件. 把文件关上. 打开文件 打开文件用open()函数,打开成功后返回一个资源,具体语法如下. open(要打开的文件,打开方式,打开文件的格式, ...
随机推荐
- [转]ORACLE分区表的使用和管理
转自:http://love-flying-snow.iteye.com/blog/573303 废话少说,直接讲分区语法. Oracle表分区分为四种:范围分区,散列分区,列表分区和复合分区. 一: ...
- 从cdn说起
为什么要使用cdn 雅虎军规有一条规则建议我们是用cdn.随便在网上搜索,可以找到使用的cdn的好处. 再次强调第一条黄金定律,减少网页内容的下载时间.提高下载速度还可以通过CDN(内容分发网络)来提 ...
- 坐忘峰 golang入坑系列
读前必读: 本文写于20日,首发于gitbook. 迟到的是日期,没变的是内容. 点击进入 https://andy-zhangtao.gitbooks.io/golang/content/ 可以看到 ...
- 前端使用d3.js调用地图api 进行数据可视化
前段时间自己研究了demo就是把某个区域的某个位置通过经纬度在地图上可视化.其实就是使用了第三方插件,比现在比较火的可视化插件d3.js echart.js.大致思路就是,把要用到的位置的geojso ...
- css实现六边形图片(最简单易懂方法实现高逼格图片展示)
不说别的,先上效果: 用简单的div配合伪元素,即可‘画出’这幅六边形图片,原理是三个相同宽高的div,通过定位旋转拼合成一个六边形,再利用背景图层叠,形成视觉上的一张整图.下面咱们一步一步来实现. ...
- C语言之二维数组棋盘游戏
#include<iostream> #include<stdio.h> using namespace std; int main() { //-1 没人赢 0:O赢 1:X ...
- Java中的回调
又忙了一周,事情差不多解决了,终于有可以继续写我的博客了(各位看官久等了). 这次我们来谈一谈Java里的一个很有意思的东西--回调. 什么叫回调,一本正经的来讲,在计算机程序设计中,回调函数是指通过 ...
- 【原创】2、小程序域名配置之申请支持SSL(https)
要把一个网站对接进小程序,一.网站的域名必须通过备案(ICP备案).在买域名的时候,各个域名服务商都有提供相应的备案平台,可以方便的提交备案.工信部官网:http://www.miitbeian.go ...
- Ocelot网关
Ocelot是一个.net core框架下的网关的开源项目,下图是官方给出的基础实现图,即把后台的多个服务统一到网关处,前端应用:桌面端,web端,app端都只用访问网关即可. Ocelot的实现原理 ...
- yii框架开启事务
public function actionAdd() { $model = new Goods(); $model->setScenario('insert'); if ($model-> ...