铁乐学Python_day08_文件操作

一、【基本的文件操作】

参数:
1、文件路径;
2、编码方式;
3、执行动作;(打开方式)只读,只写,追加,读写,写读!

#1. 打开文件,得到文件句柄并赋值给一个变量
f = open('E:/Python/file/文件操作测试.txt', encoding='utf-8', mode='r')
content = f.read()
print(content)
f.close()

E:PythonvenvScriptspython.exe E:/Python/day08/文件操作.py
文件操作测试读取,2018-3-27
read

f:变量,f_obj,file,f_handler,...文件句柄。
open --- windows的系统功能,
windows默认编码方式:gbk,
linux默认编码方式:utf-8。
f.close() --- 关闭文件(保存退出)

流程:
1、打开一个文件,产生一个文件句柄,
2、通过句柄对文件进行操作,
3、关闭文件。

二、【关闭文件的注意事项】

打开一个文件包含两部分资源:操作系统级打开的文件+应用程序的变量。
在操作完毕一个文件时,必须把与该文件的这两部分资源一个不落地回收,回收方法为:
1、f.close() #回收操作系统级打开的文件
2、del f #回收应用程序级的变量

其中del f一定要发生在f.close()之后,
否则就会导致操作系统打开的文件还没有关闭,白白占用资源,
python自动的垃圾回收机制决定了无需考虑del f,在操作完毕文件后,记住f.close()就可以了。

推荐傻瓜式操作方式:使用with关键字来帮我们管理上下文的同时自动关闭文件。

【with】
功能一:自动关闭文件句柄
功能二:一次性操作多个文件句柄

例:

with open('a.txt', encoding='utf-8', 'w') as f:
    pass

with open('a.txt', encondig='utf-8', 'w') as read_f,open('b.txt','w') as write_f:
    data=read_f.read()
    write_f.write(data)

三、【文件的打开模式】

文件句柄 = open(‘文件路径’,‘模式’)

1、文件以什么编码方式存储的,就以什么编码方式打开;
2、文件路径:
绝对路径:从根目录开始
相对路径:从打开软件所在的路径开始(比如pycharm就是在pycharm的工作目录起)

1. 打开文件的模式有(默认为文本模式):

r, 只读模式【默认模式,文件必须存在,不存在则抛出异常】
w, 只写模式【不可读;文件不存在则创建文件;存在则清空内容】
a, 只追加写模式【不可读;文件不存在则创建;存在则只追加内容】

2. 对于非文本文件,(例如图片)可以使用b模式,"b"表示以字节的方式操作(而所有文件也都是以字节的形式存储的,使用这种模式无需考虑文本文件的字符编码、图片文件的jgp格式、视频文件的avi格式)

rb
wb
ab
具体同上,只是后面加了个b表示是b模式。
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码。

3,‘+’模式(就是增加了一个功能)

r+, 读写【可读,可写】
w+, 写读【可写,可读】
a+, 追加方式的写读【可写,可读】

4,以bytes类型操作的读写,写读,写读模式

r+b, 读写【可读,可写】
w+b, 写读【可写,可读】
a+b, 追加写读【可写,可读】

四、【文件操作方式】

【读模式操作方式】
read()
全部一次性读取(有缺点:要是一次性读取超大文件会爆内存,例如linux上的日志文件。)

readline()
每次读取一行(并且文件内光标随之移动到第二行头部)

readlines()
将原文件的每一行作为一个元素放在列表当中(包括 换行符)可加.strip去掉换行符

read(n)
在r模式下,按字符去读取n个字符
在rb模式下,按字节去读取n个字节

适合读取超大文件的方法:
循环读取,全部能读取出来而且在内存当中永远只占一行。
因为每次都是读取一行清除一行的内存在去读取下一行。

例:循环读取。

# f = open('log',encoding='utf-8')
# for i in f:
#     print(i.strip())
# f.close()

【光标】
文件内光标移动都是以字节为单位的如:seek,tell,truncate
f.tell() # 按字节去读取光标位置
f.seek() # 按字节调整光标位置

file.seek()方法格式:
seek(offset,whence=0)
移动文件读取指针(移动光标)到指定位置。

offset:开始的偏移量,也就是代表需要移动偏移的字节数。

whence(移动模式): 给offset参数一个定义,表示要从哪个位置开始偏移;
0代表从文件开头算起,
1代表开始从当前位置开始算起,
2代表从文件末尾开始算起。当有换行时,会被换行截断。

seek的三种移动方式0,1,2,其中1和2必须在b模式下进行,但无论哪种模式,都是以bytes为单位移动的。
seek()无返回值,故值为None

file.truncate():
truncate(),对文字内容进行截取。
truncate是截断文件,所以文件的打开方式必须可写,但是不能用w或w+等方式打开,
因为那样直接清空文件了,所以truncate要在r+或a或a+等模式下测试效果。

【官方源码参考】

class file(object)
    def close(self): # real signature unknown; restored from __doc__
        关闭文件
        """
        close() -> None or (perhaps) an integer.  Close the file.

        Sets data attribute .closed to True.  A closed file cannot be used for
        further I/O operations.  close() may be called more than once without
        error.  Some kinds of file objects (for example, opened by popen())
        may return an exit status upon closing.
        """

    def fileno(self): # real signature unknown; restored from __doc__
        文件描述符  
         """
        fileno() -> integer "file descriptor".

        This is needed for lower-level file interfaces, such os.read().
        """
        return 0    

    def flush(self): # real signature unknown; restored from __doc__
        刷新文件内部缓冲区(类似于文件-保存的效果)
        """ flush() -> None.  Flush the internal I/O buffer. """
        pass

    def isatty(self): # real signature unknown; restored from __doc__
        判断文件是否是同意tty设备
        """ isatty() -> true or false.  True if the file is connected to a tty device. """
        return False

    def next(self): # real signature unknown; restored from __doc__
        获取下一行数据,不存在,则报错
        """ x.next() -> the next value, or raise StopIteration """
        pass

    def read(self, size=None): # real signature unknown; restored from __doc__
        读取指定字节数据
        """
        read([size]) -> read at most size bytes, returned as a string.

        If the size argument is negative or omitted, read until EOF is reached.
        Notice that when in non-blocking mode, less data than what was requested
        may be returned, even if no size parameter was given.
        """
        pass

    def readinto(self): # real signature unknown; restored from __doc__
        读取到缓冲区,不要用,将被遗弃
        """ readinto() -> Undocumented.  Don't use this; it may go away. """
        pass

    def readline(self, size=None): # real signature unknown; restored from __doc__
        仅读取一行数据
        """
        readline([size]) -> next line from the file, as a string.

        Retain newline.  A non-negative size argument limits the maximum
        number of bytes to return (an incomplete line may be returned then).
        Return an empty string at EOF.
        """
        pass

    def readlines(self, size=None): # real signature unknown; restored from __doc__
        读取所有数据,并根据换行保存值到列表
        """
        readlines([size]) -> list of strings, each a line from the file.

        Call readline() repeatedly and return a list of the lines so read.
        The optional size argument, if given, is an approximate bound on the
        total number of bytes in the lines returned.
        """
        return []

    def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
        指定文件中指针位置
        """
        seek(offset[, whence]) -> None.  Move to new file position.

        Argument offset is a byte count.  Optional argument whence defaults to
(offset from start of file, offset should be >= 0); other values are 1
        (move relative to current position, positive or negative), and 2 (move
        relative to end of file, usually negative, although many platforms allow
        seeking beyond the end of a file).  If the file is opened in text mode,
        only offsets returned by tell() are legal.  Use of other offsets causes
        undefined behavior.
        Note that not all file objects are seekable.
        """
        pass

    def tell(self): # real signature unknown; restored from __doc__
        获取当前指针位置
        """ tell() -> current file position, an integer (may be a long integer). """
        pass

    def truncate(self, size=None): # real signature unknown; restored from __doc__
        截断数据,仅保留指定之前数据
        """
        truncate([size]) -> None.  Truncate the file to at most size bytes.

        Size defaults to the current file position, as returned by tell().
        """
        pass

    def write(self, p_str): # real signature unknown; restored from __doc__
        写内容
        """
        write(str) -> None.  Write string str to file.

        Note that due to buffering, flush() or close() may be needed before
        the file on disk reflects the data written.
        """
        pass

    def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
        将一个字符串列表写入文件
        """
        writelines(sequence_of_strings) -> None.  Write the strings to the file.

        Note that newlines are not added.  The sequence can be any iterable object
        producing strings. This is equivalent to calling write() for each string.
        """
        pass

    def xreadlines(self): # real signature unknown; restored from __doc__
        可用于逐行读取文件,非全部
        """
        xreadlines() -> returns self.

        For backward compatibility. File objects now include the performance
        optimizations previously implemented in the xreadlines module.
        """
        pass

五、【文件的修改】

文件的数据是存放于硬盘上的,因而实际上底层只存在覆盖、不存在修改这么一说,
我们平时看到的修改编辑文件,都是模拟出来的效果,具体的说有两种实现方式:

方式一:将硬盘存放的该文件的内容全部加载到内存,在内存中是可以修改的,修改完毕后,再由内存覆盖到硬盘(word,vim,nodpad++等编辑器)

---------------------------
import os  # 调用系统模块

with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:
    data=read_f.read() #全部读入内存,如果文件很大,会很卡
    data=data.replace('old','new') #在内存中完成修改,将旧内容替换成新内容

    write_f.write(data) #一次性写入新文件

os.remove('a.txt')  #删除原文件
# 因为不删除将建立不了同名的文件,其实我感觉上先将原文件改名再让新文件命名成原文件名后确认无误后再删除原文件更安全保险。
os.rename('.a.txt.swap','a.txt')   #将新建的文件重命名为原文件
-----------------------------

方式二:将硬盘存放的该文件的内容一行一行地读入内存,修改完毕就写入新文件,最后用新文件覆盖源文件。

import os

with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:
    for line in read_f:
        line=line.replace('old','new')
        write_f.write(line)

os.remove('a.txt')
os.rename('.a.txt.swap','a.txt') 

简述为以下流程:
1、将源文件读取到内存;
2、在内存中时行修改,形成新的字符串(文件);
3、将新的字符串写入新文件;
3、将原文件删除;
4、将新文件重命名为原文件。

例:有如下文件:
-------
alex是老男孩python发起人,创建人。
alex其实是人妖。
谁说alex是sb?
你们真逗,alex再牛逼,也掩饰不住资深屌丝的气质。
----------
将文件中所有的alex都替换成大写的SB。

答:

with open('log',encoding='utf-8') as f1,
    open('log.bak',encoding='utf-8',mode='w') as f2:
    content = f1.read()
    new_content = content.replace('alex','SB')
    f2.write(new_content)
os.remove('log')
os.rename('log.bak','log')

import os
with open('log',encoding='utf-8') as f1,
    open('log.bak',encoding='utf-8',mode='w') as f2:
    for i in f1:
        new_i = i.replace('SB','alex')
        f2.write(new_i)
os.remove('log')
os.rename('log.bak','log')

end
2018-4-2

原文地址:https://www.cnblogs.com/tielemao/p/8698478.html