文件操作

对文件操作流程

  1. 打开文件,得到文件句柄并赋值给一个变量
  2. 通过句柄对文件进行操作
  3. 关闭文件

现有文件如下

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
 
= 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
f.flush()  强制刷新
进度条
import sys,time
 
for i in range(20):
  sys.stdout.write('#')  #标准输出 stdout
  sys.stdout.flush()
  time.sleep(0.1)
 
f.replace(修改前,修改后)  文件修改
 
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 文件操作的更多相关文章

  1. 小白的Python之路 day2 字符串操作 , 字典操作

    1. 字符串操作 特性:不可修改 name.capitalize() 首字母大写 name.casefold() 大写全部变小写 name.center(50,"-") 输出 '- ...

  2. python之路(五)-文件操作

    文件操作无非两个,即:读.写 python 2.x: 文件句柄 = file('文件路径', '模式') python3.x: 文件句柄 = open('文件路径', '模式') 打开文件的模式有: ...

  3. python之路---08 文件操作

    二十六.   文件 f = open(文件路径,mode = '模式',encoding = '编码格式') 1.基础 ① 读写时,主要看光标的位置 ②操作完成要写    f.close( ) f.f ...

  4. Python之路 day2 文件基础操作

    #!/usr/bin/env python # -*- coding:utf-8 -*- #Author:ersa ''' #f,文件句柄;模式 a : append 追加文件内容 f = open( ...

  5. 小白的Python之路 day2 列表、元组操作

    1. 列表.元组操作 列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储.修改等操作 定义列表 1 names = ['Tom','Jack','Qian'] 通过下标访问列表中 ...

  6. 小白学习Python之路---py文件转换成exe可执行文件

    一.背景 今天闲着无事,写了一个小小的Python脚本程序,然后给同学炫耀的时候,发现每次都得拉着其他人过来看着自己的电脑屏幕,感觉不是很爽,然后我想着网上肯定有关于Python脚本转换成可执行文件的 ...

  7. 小白的Python之路 day2 字符编码和转码

    字符编码和转码 详细文章: http://www.cnblogs.com/yuanchenqi/articles/5956943.html http://www.diveintopython3.net ...

  8. python成长之路五-文件操作

    1,文件操作 f = open("D:\种子.txt",encoding="utf-8",mode="r") # 打开一个种子.txt文件, ...

  9. Python学习之路4 - 文件操作&编码转换

    文件操作 文件操作大概分三步: 把文件打开. 操作文件. 把文件关上. 打开文件 打开文件用open()函数,打开成功后返回一个资源,具体语法如下. open(要打开的文件,打开方式,打开文件的格式, ...

随机推荐

  1. 利用VGG19实现火灾分类(附tensorflow代码及训练集)

    源码地址 https://github.com/stephen-v/tensorflow_vgg_classify 1. VGG介绍 1.1. VGG模型结构 1.2. VGG19架构 2. 用Ten ...

  2. 2734:十进制到八进制-poj

    总时间限制:  1000ms 内存限制:  65536kB 描述 把一个十进制正整数转化成八进制. 输入 一行,仅含一个十进制表示的整数a(0 < a < 65536). 输出 一行,a的 ...

  3. CPU 虚拟化

    前面 虚拟化技术总览 中从虚拟平台 VMM 的角度,将虚拟化分为 Hypervisor 模型和宿主模型,如果根据虚拟的对象(资源类型)来划分,虚拟化又可以分为计算虚拟化.存储虚拟化和网络虚拟化,再细一 ...

  4. 11个优秀的Android开发开源项目

    一. 一个类似微信的时光轴效果   时光轴效果 项目地址 https://github.com/ljtyzhr/TimeLine 二. 安卓选择器类库,包括日期.时间.单项.双项选择器.城市地址选择器 ...

  5. ShoneSharp语言(S#)的设计和使用介绍系列(4)— 入门概述

    ShoneSharp语言(S#)的设计和使用介绍 系列(4)- 入门概述 作者:Shone 声明:原创文章欢迎转载,但请注明出处,https://www.cnblogs.com/ShoneSharp. ...

  6. QQ空间掉帧率优化实战

    商业转载请联系腾讯WeTest获得授权,非商业转载请注明出处. WeTest 导读 空间新业务需求日益增多,在业务开发阶段的疏忽,或者是受到其他业务的影响(比如一些非空间的业务网络回包或者逻辑在主线程 ...

  7. python使用rsa库做公钥解密(网上别处找不到)

    使用RSA公钥解密,用openssl命令就是openssl rsautl -verify -in cipher_text -inkey public.pem -pubin -out clear_tex ...

  8. macbookPro 搭建maven环境下载jar包

    今天要用itext的jar包,去官网看发现好像只能用maven下载,而我之前又换了电话,没办法咯,重新搭一次maven环境吧,在此记录,已便分享或自己将来查找 首选确定自己环境上jdk装好了,如果没有 ...

  9. Batch Normalization

    一.BN 的作用 1.具有快速训练收敛的特性:采用初始很大的学习率,然后学习率的衰减速度也很大 2.具有提高网络泛化能力的特性:不用去理会过拟合中drop out.L2正则项参数的选择问题 3.不需要 ...

  10. Postgresql中的explain

    PostgreSQL为每个收到的查询设计一个查询规划.选择正确的匹配查询结构和数据属性的规划对执行效率是至关重要要的,所以系统包含一个复杂的规划器来试图选择好的规划.你可以使用EXPLAIN命令查看查 ...