威尼斯人线上娱乐

python文件操作,python之文件操作

28 3月 , 2019  

微型总计机种类分为:硬件,操作系统,应用程序

一,文件操作基本流程。

总括机种类分为:计算机硬件,操作系统,应用程序三有些。

作者们用python或其余语言编写的应用程序若想要把多少永久保存下去,必须要保留于硬盘中,这就涉嫌到应用程序要操作硬件,有目共睹,应用程序是不只怕直接操作硬件的,那就用到了操作系统。操作系统把复杂的硬件操作封装成简单的接口给用户/应用程序使用,当中文件正是操作系统提需求应用程序来操作硬盘虚拟概念,用户或应用程序通过操作文件,能够将协调的数量永久保存下来。

有了文本的定义,我们无需再去考虑操作硬盘的底细,只必要关注操作文件的流程:

#1. 打开文件,得到文件句柄并赋值给一个变量
f=open('a.txt','r',encoding='utf-8') #默认打开模式就为r

#2. 通过句柄对文件进行操作
data=f.read()

#3. 关闭文件
f.close()

 

回去目录页

一. 文书操作基本流程

处理器体系分为:总计机硬件,操作系统,应用程序三局地。

我们用python或别的语言编写的应用程序若想要把多少永久保存下来,必必要保留于硬盘中,那就涉及到应用程序要操作硬件,闻名遐迩,应用程序是无能为力直接操作硬件的,那就用到了操作系统。操作系统把复杂的硬件操作封装成不难的接口给用户/应用程序使用,其中文件就是操作系统提要求应用程序来操作硬盘虚拟概念,用户或应用程序通过操作文件,能够将本身的多寡永久保存下去。

有了文本的定义,大家无需再去考虑操作硬盘的底细,只须要关爱操作文件的流水生产线:

#1. 打开文件,得到文件句柄并赋值给一个变量
f=open('a.txt','r',encoding='utf-8') #默认打开模式就为r

#2. 通过句柄对文件进行操作
data=f.read()

#3. 关闭文件
f.close()

硬件:目的在于运营软件产生的命令。硬件包罗CPU,内部存款和储蓄器,硬盘

闭馆文件的注意事项:

威尼斯人线上娱乐 1威尼斯人线上娱乐 2

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

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

虽然我这么说,但是很多同学还是会很不要脸地忘记f.close(),对于这些不长脑子的同学,我们推荐傻瓜式操作方式:使用with关键字来帮我们管理上下文
with open('a.txt','w') as f:
    pass

with open('a.txt','r') as read_f,open('b.txt','w') as write_f:
    data=read_f.read()
    write_f.write(data)

注意

View Code

 

 

文本操作基本流程

电脑种类分为:计算机硬件,操作系统,应用程序三局地。

咱俩用python或别的语言编写的应用程序若想要把多少永久保存下来,须要求保留于硬盘中,那就涉及到应用程序要操作硬件,远近著名,应用程序是无能为力直接操作硬件的,那就用到了操作系统。操作系统把复杂的硬件操作封装成简单的接口给用户/应用程序使用,其普通话件正是操作系统提供给应用程序来操作硬盘虚拟概念,用户或应用程序通过操作文件,能够将自身的数量永久保存下来。

有了文本的概念,大家无需再去考虑操作硬盘的细节,只供给关爱操作文件的流程:

#1. 打开文件,得到文件句柄并赋值给一个变量
f=open('a.txt','r',encoding='utf-8') #默认打开模式就为r

#2. 通过句柄对文件进行操作
data=f.read()

#3. 关闭文件
f.close()

关门文件的注意事项:

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

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

虽然我这么说,但是很多同学还是会很不要脸地忘记f.close(),对于这些不长脑子的同学,我们推荐傻瓜式操作方式:使用with关键字来帮我们管理上下文
with open('a.txt','w') as f:
    pass

with open('a.txt','r') as read_f,open('b.txt','w') as write_f:
    data=read_f.read()
    write_f.write(data)

注意

大部分CPU都有二种方式,即内核态与用户态。
       

二,文件编码

f=open(…)是由操作系统打开文件,那么一旦大家尚无为open指确定人员编制码,那么打开文件的私下认可编码很明朗是操作系统说了算了,操作系统会用自身的暗中认可编码去开拓文件,在windows下是gbk,在linux下是utf-8。

#这就用到了上节课讲的字符编码的知识:若要保证不乱码,文件以什么方式存的,就要以什么方式打开。
f=open('a.txt','r',encoding='utf-8')

 

关门文件的注意事项:

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

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

虽然我这么说,但是很多同学还是会很不要脸地忘记f.close(),对于这些不长脑子的同学,我们推荐傻瓜式操作方式:使用with关键字来帮我们管理上下文
with open('a.txt','w') as f:
    pass

with open('a.txt','r') as read_f,open('b.txt','w') as write_f:
    data=read_f.read()
    write_f.write(data)

二. 文件编码

f=open(…)

是由操作系统打开文件,那么一旦我们没有为open钦赐编码,那么打开文件的暗中认可编码很分明是操作系统说了算了

操作系统会用自身的暗中认可编码去开拓文件,在windows下是gbk,在linux下是utf-8。

#这就用到了上节课讲的字符编码的知识:若要保证不乱码,文件以什么方式存的,就要以什么方式打开。
f=open('a.txt','r',encoding='utf-8')

①当cpu处于根本状态时,运转的是操作系统,能说了算硬件(能够赢得具有cpu的指令集)     

三,文件的打开方式

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

#1. 打开文件的模式有(默认为文本模式):
r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
w,只写模式【不可读;不存在则创建;存在则清空内容】
a, 只追加写模式【不可读;不存在则创建;存在则只追加内容】

#2. 对于非文本文件,我们只能使用b模式,"b"表示以字节的方式操作(而所有文件也都是以字节的形式存储的,使用这种模式无需考虑文本文件的字符编码、图片文件的jgp格式、视频文件的avi格式)
rb 
wb
ab
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码

#3,‘+’模式(就是增加了一个功能)
r+, 读写【可读,可写】
w+,写读【可写,可读】
a+, 写读【可写,可读】

#4,以bytes类型操作的读写,写读,写读模式
r+b, 读写【可读,可写】
w+b,写读【可写,可读】
a+b, 写读【可写,可读】

 

文本编码

f=open(…)是由操作系统打开文件,那么只要大家从没为open钦命编码,那么打开文件的暗中同意编码很扎眼是操作系统说了算了,操作系统会用本人的私下认可编码去开拓文件,在windows下是gbk,在linux下是utf-8。

#这就用到了上节课讲的字符编码的知识:若要保证不乱码,文件以什么方式存的,就要以什么方式打开。
f=open('a.txt','r',encoding='utf-8')

三. 文件的开拓情势

文件句柄 = open(‘文件路径’,‘格局’)

#1. 打开文件的模式有(默认为文本模式):
r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
w,只写模式【不可读;不存在则创建;存在则清空内容】
a, 只追加写模式【不可读;不存在则创建;存在则只追加内容】

#2. 对于非文本文件,我们只能使用b模式,"b"表示以字节的方式操作(而所有文件也都是以字节的形式存储的,使用这种模式无需考虑文本文件的字符编码、图片文件的jgp格式、视频文件的avi格式)
rb 
wb
ab
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码

#3,‘+’模式(就是增加了一个功能)
r+, 读写【可读,可写】
w+,写读【可写,可读】
a+, 写读【可写,可读】

#4,以bytes类型操作的读写,写读,写读模式
r+b, 读写【可读,可写】
w+b,写读【可写,可读】
a+b, 写读【可写,可读】

②当cpu处于用户太状态时,运转的是用户软件,无法说了算硬件(能够赢得具有cpu的吩咐集中的三个子集,该子集不包蕴操作硬件的指令集)

 四,文件操作方法。

文本的打开形式

文本句柄 = open(‘文件路径’,‘格局’)

#1. 打开文件的模式有(默认为文本模式):
r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
w,只写模式【不可读;不存在则创建;存在则清空内容】
a, 只追加写模式【不可读;不存在则创建;存在则只追加内容】

#2. 对于非文本文件,我们只能使用b模式,"b"表示以字节的方式操作(而所有文件也都是以字节的形式存储的,使用这种模式无需考虑文本文件的字符编码、图片文件的jgp格式、视频文件的avi格式)
rb 
wb
ab
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码

#3,‘+’模式(就是增加了一个功能)
r+, 读写【可读,可写】
w+,写读【可写,可读】
a+, 写读【可写,可读】

#4,以bytes类型操作的读写,写读,写读模式
r+b, 读写【可读,可写】
w+b,写读【可写,可读】
a+b, 写读【可写,可读】

四. 文件操作方法

威尼斯人线上娱乐 3 

4.1常用操作方法。

read(3):

  1. 文书打开药情势为文本形式时,代表读取三个字符

  2. 文件打开药格局为b格局时,代表读取二个字节

其余的文本内光标移动都以以字节为单位的如:seek,tell,truncate

注意:

  1.
seek有三种运动格局0,1,2,当中1和2务必在b形式下进行,但不论哪一种情势,都是以bytes为单位活动的

python文件操作,python之文件操作。  2.
truncate是截断文件,所以文件的打开药格局必须可写,可是不可能用w或w+等措施打开,因为那样直接清空文件了,所以truncate要在r+或a或a+等情势下测试效果。

文件操作方法

4.1常用操作方法

read(3):

  1. 文书打开格局为文本方式时,代表读取3个字符

  2. 文书打开药格局为b格局时,代表读取二个字节

其他的公文内光标移动都以以字节为单位的如:seek,tell,truncate

注意:

  1.
seek有两种运动形式0,1,2,当中1和2必须在b方式下举办,但无论哪个种类方式,都以以bytes为单位活动的

  2.
truncate是截断文件,所以文件的打开格局必须可写,可是无法用w或w+等办法打开,因为那样直接清空文件了,所以truncate要在r+或a或a+等情势下测试效果。

有关文件:

4.2拥有操作方法。

威尼斯人线上娱乐 4威尼斯人线上娱乐 5

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

2.x

2.x

威尼斯人线上娱乐 6威尼斯人线上娱乐 7

class TextIOWrapper(_TextIOBase):
    """
    Character and line based layer over a BufferedIOBase object, buffer.

    encoding gives the name of the encoding that the stream will be
    decoded or encoded with. It defaults to locale.getpreferredencoding(False).

    errors determines the strictness of encoding and decoding (see
    help(codecs.Codec) or the documentation for codecs.register) and
    defaults to "strict".

    newline controls how line endings are handled. It can be None, '',
    '\n', '\r', and '\r\n'.  It works as follows:

    * On input, if newline is None, universal newlines mode is
      enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
      these are translated into '\n' before being returned to the
      caller. If it is '', universal newline mode is enabled, but line
      endings are returned to the caller untranslated. If it has any of
      the other legal values, input lines are only terminated by the given
      string, and the line ending is returned to the caller untranslated.

    * On output, if newline is None, any '\n' characters written are
      translated to the system default line separator, os.linesep. If
      newline is '' or '\n', no translation takes place. If newline is any
      of the other legal values, any '\n' characters written are translated
      to the given string.

    If line_buffering is True, a call to flush is implied when a call to
    write contains a newline character.
    """
    def close(self, *args, **kwargs): # real signature unknown
        关闭文件
        pass

    def fileno(self, *args, **kwargs): # real signature unknown
        文件描述符  
        pass

    def flush(self, *args, **kwargs): # real signature unknown
        刷新文件内部缓冲区
        pass

    def isatty(self, *args, **kwargs): # real signature unknown
        判断文件是否是同意tty设备
        pass

    def read(self, *args, **kwargs): # real signature unknown
        读取指定字节数据
        pass

    def readable(self, *args, **kwargs): # real signature unknown
        是否可读
        pass

    def readline(self, *args, **kwargs): # real signature unknown
        仅读取一行数据
        pass

    def seek(self, *args, **kwargs): # real signature unknown
        指定文件中指针位置
        pass

    def seekable(self, *args, **kwargs): # real signature unknown
        指针是否可操作
        pass

    def tell(self, *args, **kwargs): # real signature unknown
        获取指针位置
        pass

    def truncate(self, *args, **kwargs): # real signature unknown
        截断数据,仅保留指定之前数据
        pass

    def writable(self, *args, **kwargs): # real signature unknown
        是否可写
        pass

    def write(self, *args, **kwargs): # real signature unknown
        写内容
        pass

    def __getstate__(self, *args, **kwargs): # real signature unknown
        pass

    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __next__(self, *args, **kwargs): # real signature unknown
        """ Implement next(self). """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    buffer = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    closed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    encoding = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    errors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    name = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    newlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

3.x

3.x

 

常用操作方法

read(3):

  1. 文件打开方式为文本模式时,代表读取3个字符

  2. 文件打开方式为b模式时,代表读取3个字节

其余的文件内光标移动都是以字节为单位的如:seek,tell,truncate

注意:

  1. seek有三种移动方式0,1,2,其中1和2必须在b模式下进行,但无论哪种模式,都是以bytes为单位移动的

  2. truncate是截断文件,所以文件的打开方式必须可写,但是不能用w或w+等方式打开,因为那样直接清空文件了,所以truncate要在r+或a或a+等模式下测试效果。

4.2享有操作方法

威尼斯人线上娱乐 8威尼斯人线上娱乐 9

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

2.x

威尼斯人线上娱乐 10威尼斯人线上娱乐 11

class TextIOWrapper(_TextIOBase):
    """
    Character and line based layer over a BufferedIOBase object, buffer.

    encoding gives the name of the encoding that the stream will be
    decoded or encoded with. It defaults to locale.getpreferredencoding(False).

    errors determines the strictness of encoding and decoding (see
    help(codecs.Codec) or the documentation for codecs.register) and
    defaults to "strict".

    newline controls how line endings are handled. It can be None, '',
    '\n', '\r', and '\r\n'.  It works as follows:

    * On input, if newline is None, universal newlines mode is
      enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
      these are translated into '\n' before being returned to the
      caller. If it is '', universal newline mode is enabled, but line
      endings are returned to the caller untranslated. If it has any of
      the other legal values, input lines are only terminated by the given
      string, and the line ending is returned to the caller untranslated.

    * On output, if newline is None, any '\n' characters written are
      translated to the system default line separator, os.linesep. If
      newline is '' or '\n', no translation takes place. If newline is any
      of the other legal values, any '\n' characters written are translated
      to the given string.

    If line_buffering is True, a call to flush is implied when a call to
    write contains a newline character.
    """
    def close(self, *args, **kwargs): # real signature unknown
        关闭文件
        pass

    def fileno(self, *args, **kwargs): # real signature unknown
        文件描述符  
        pass

    def flush(self, *args, **kwargs): # real signature unknown
        刷新文件内部缓冲区
        pass

    def isatty(self, *args, **kwargs): # real signature unknown
        判断文件是否是同意tty设备
        pass

    def read(self, *args, **kwargs): # real signature unknown
        读取指定字节数据
        pass

    def readable(self, *args, **kwargs): # real signature unknown
        是否可读
        pass

    def readline(self, *args, **kwargs): # real signature unknown
        仅读取一行数据
        pass

    def seek(self, *args, **kwargs): # real signature unknown
        指定文件中指针位置
        pass

    def seekable(self, *args, **kwargs): # real signature unknown
        指针是否可操作
        pass

    def tell(self, *args, **kwargs): # real signature unknown
        获取指针位置
        pass

    def truncate(self, *args, **kwargs): # real signature unknown
        截断数据,仅保留指定之前数据
        pass

    def writable(self, *args, **kwargs): # real signature unknown
        是否可写
        pass

    def write(self, *args, **kwargs): # real signature unknown
        写内容
        pass

    def __getstate__(self, *args, **kwargs): # real signature unknown
        pass

    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __next__(self, *args, **kwargs): # real signature unknown
        """ Implement next(self). """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    buffer = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    closed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    encoding = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    errors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    name = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    newlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

3.x

3.x

  • 文本能够储存不相同连串的音讯,三个文件能够蕴含文本,图片,摄像,总计机程序等剧情。
  • 微型总括机上硬盘上装有的剧情都以以文件的款式储存。程序正是由三个或许八个文件构成的。
  • 文本对象是python代码对电脑上国艺术大学部文件的机要接口。

五,文件的修改。

文本的数码是存放在于硬盘上的,因而只存在覆盖、不设有修改这么一说,我们平昔看到的修改文件,都以效仿出来的效果,具体的说有三种达成方式:

格局一:将硬盘存放的该文件的内容总体加载到内存,在内部存款和储蓄器中是足以修改的,修改实现后,再由内部存款和储蓄器覆盖到硬盘(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('alex','SB') #在内存中完成修改

    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('alex','SB')
        write_f.write(line)

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

 

富有操作方法。

威尼斯人线上娱乐 12威尼斯人线上娱乐 13

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

2.x

威尼斯人线上娱乐 14威尼斯人线上娱乐 15

class TextIOWrapper(_TextIOBase):
    """
    Character and line based layer over a BufferedIOBase object, buffer.

    encoding gives the name of the encoding that the stream will be
    decoded or encoded with. It defaults to locale.getpreferredencoding(False).

    errors determines the strictness of encoding and decoding (see
    help(codecs.Codec) or the documentation for codecs.register) and
    defaults to "strict".

    newline controls how line endings are handled. It can be None, '',
    '\n', '\r', and '\r\n'.  It works as follows:

    * On input, if newline is None, universal newlines mode is
      enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
      these are translated into '\n' before being returned to the
      caller. If it is '', universal newline mode is enabled, but line
      endings are returned to the caller untranslated. If it has any of
      the other legal values, input lines are only terminated by the given
      string, and the line ending is returned to the caller untranslated.

    * On output, if newline is None, any '\n' characters written are
      translated to the system default line separator, os.linesep. If
      newline is '' or '\n', no translation takes place. If newline is any
      of the other legal values, any '\n' characters written are translated
      to the given string.

    If line_buffering is True, a call to flush is implied when a call to
    write contains a newline character.
    """
    def close(self, *args, **kwargs): # real signature unknown
        关闭文件
        pass

    def fileno(self, *args, **kwargs): # real signature unknown
        文件描述符  
        pass

    def flush(self, *args, **kwargs): # real signature unknown
        刷新文件内部缓冲区
        pass

    def isatty(self, *args, **kwargs): # real signature unknown
        判断文件是否是同意tty设备
        pass

    def read(self, *args, **kwargs): # real signature unknown
        读取指定字节数据
        pass

    def readable(self, *args, **kwargs): # real signature unknown
        是否可读
        pass

    def readline(self, *args, **kwargs): # real signature unknown
        仅读取一行数据
        pass

    def seek(self, *args, **kwargs): # real signature unknown
        指定文件中指针位置
        pass

    def seekable(self, *args, **kwargs): # real signature unknown
        指针是否可操作
        pass

    def tell(self, *args, **kwargs): # real signature unknown
        获取指针位置
        pass

    def truncate(self, *args, **kwargs): # real signature unknown
        截断数据,仅保留指定之前数据
        pass

    def writable(self, *args, **kwargs): # real signature unknown
        是否可写
        pass

    def write(self, *args, **kwargs): # real signature unknown
        写内容
        pass

    def __getstate__(self, *args, **kwargs): # real signature unknown
        pass

    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __next__(self, *args, **kwargs): # real signature unknown
        """ Implement next(self). """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    buffer = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    closed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    encoding = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    errors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    name = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    newlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

3.x

五. 文件的修改

文本的数据是存放于硬盘上的,由此只设有覆盖、不设有修改这么一说,大家平常收看的修改文件,都是效仿出来的功效,具体的说有二种达成格局:

情势一:将硬盘存放的该文件的内容总体加载到内部存款和储蓄器,在内部存款和储蓄器中是足以修改的,修改完毕后,再由内部存款和储蓄器覆盖到硬盘(word,vim,nodpad++等编辑器)

威尼斯人线上娱乐 16威尼斯人线上娱乐 17

import os  # 调用系统模块

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

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

os.remove('a.txt')  #删除原文件
os.rename('.a.txt.swap','a.txt')   #将新建的文件重命名为原文件

方法一

方法二:将硬盘存放的该公文的情节一行一行地读入内存,修改完结就写入新文件,最终用新文件覆盖源文件

威尼斯人线上娱乐 18威尼斯人线上娱乐 19

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('alex','SB')
        write_f.write(line)

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

方法二

文件属性:

六,当日演习。

  1. 文件a.txt内容:每一行内容分别为货物名字,价钱,个数。

apple 10 3

tesla 100000 1

mac 3000 2

lenovo 30000 3

chicken 10 3

由此代码,将其创设成那种数据类型:[{‘name’:’apple’,’price’:10,’amount’:3},{‘name’:’tesla’,’price’:1000000,’amount’:1}……]
并总结出总价钱。

2,有如下文件:


alex是老男孩python发起人,创立人。

alex其实是人妖。

谁说alex是sb?

你们真逗,alex再牛逼,也掩盖不住资深屌丝的风姿。


将文件中全部的alex都替换到大写的SB。

 

文本的改动

文件的数目是存放于硬盘上的,由此只设有覆盖、不设有修改这么一说,大家日常来看的修改文件,都以模仿出来的意义,具体的说有三种完结方式:

六. 当日演练

  1. 文件a.txt内容:每一行内容分别为货物名字,价钱,个数。

apple 10 3

tesla 100000 1

mac 3000 2

lenovo 30000 3

chicken 10 3

透过代码,将其塑造成那种数据类型:[{‘name’:’apple’,’price’:10,’amount’:3},{‘name’:’tesla’,’price’:1000000,’amount’:1}……]
并总结出总价钱。

2,有如下文件:


alex是老男孩python发起人,创立人。

alex其实是人妖。

谁说alex是sb?

你们真逗,alex再牛逼,也掩盖不住资深屌丝的风度。


将文件中享有的alex都替换来大写的SB。

  名字

方式一:

将硬盘存放的该文件的始末全方位加载到内部存款和储蓄器,在内部存储器中是能够修改的,修改完成后,再由内部存款和储蓄器覆盖到硬盘(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('alex','SB') #在内存中完成修改

    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('alex','SB')
        write_f.write(line)

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

  地方(存款和储蓄在哪个地方)

同一天练习

  1. 文件a.txt内容:每一行内容分别为货品名字,价钱,个数。

apple 10 3

tesla 100000 1

mac 3000 2

lenovo 30000 3

chicken 10 3

因此代码,将其创设成那种数据类型:[{‘name’:’apple’,’price’:10,’amount’:3},{‘name’:’tesla’,’price’:1000000,’amount’:1}……]
并盘算出总价钱。

2,有如下文件:


alex是老男孩python发起人,创设人。

alex其实是人妖。

谁说alex是sb?

你们真逗,alex再牛逼,也掩饰不住资深屌丝的神韵。


将文件中拥有的alex都替换来大写的SB。

  大小(文件中有多少字节)

文件名:

  大多数操作系统中(包括Windows),文件名中有局部用来提示文件中包涵怎么样项目标数目。文件名中常见最少有三个点(.),点前边的有的建议了文件的种类。这一部分号称扩展名(extension)

如:my_letter.txt中的扩大名是.txt,代表“文本”,

  my_letter.exe中,增加名.exe,代表“可执行文件”

 文件基础用法提醒:

文件迭代器是最好的读取行工具
内容是字符串,不是对象  
close时通常选项,调用close会终止对外部文件的连接
文件是缓冲的并且是可查找的

有关文件路径难题:

  各样文件都要存款和储蓄在有个别地方,所以除了文件名以外,每种文件还有相应的地方,硬盘和任何存款和储蓄介质都集体为文件夹或目录。

  文件夹(folder)和目录(directorie)表示的是同一样东西,只是名字分裂而已。文件夹或目录协会和关联的措施叫做文件夹结构或目录结构。

  位于其余文件夹中的文件夹称为子文件夹(subfolder),假若用目录描述则变成子目录(subdirectory)

威尼斯人线上娱乐 20

 

该公文路径:‪C:\python36\Tools\scripts\__pycache__

tips:斜线(\和/)的正确利用,在路线名中那两者都接受,可是为了以免万一报错,最佳使用/,假诺应用\有时会和前面字母形成转译符,如\t,假设您非要使用,可以运用\\

地点路径被誉为相对路径:从根目录起头,一流超级查找文件,直到找到文件。

   
 其余还有绝对路径:在平等文件夹下,直接写文件名即可。

4.1操作文件流程:

操作文件前务必的难忘,文件以怎么着编码情势存款和储蓄,就要以什么编码方式打开,不然会很不难报错。

#1. 打开文件,得到文件句柄并赋值给一个变量
f=open('a.txt', mode = 'r', encoding='utf-8')   #默认打开模式就为r

#2. 通过句柄对文件进行操作
data=f.read()  # 读取文件内容
data = f.readlines()  # 读取文件的所有行,直至文件末尾,包括每行换行字符\n,输出的是一个列表
data = f.readline()   # 一次只读取文件的一行,如果再在一个程序中使用它,python会记住当前位置,第二次使用会得到第二行 ,输出的是字符串
data = f.read(n)  # 在r模式下,read(n)按照字符去读取。在rb模式下,read(n)按照字节去读取。
循环读取:
f = open('log.txt',encoding='utf-8')
for i in f:
  print(i.strip())   # 每次读取一行,好处在于节省内存
f.close()

f.seek(0)   #如果使用了好几次readline,现在想退回到文件起始位置,可以使用该方法。其中括号里的数字是从文件起始位置算起的字节数
#3. 关闭文件
f.close()      #这个步骤很关键,可以帮助节省资源

关闭文件注意事项:
打开一个文件包含两部分资源:操作系统级打开的文件+应用程序的变量。在操作完毕一个文件时,必须把与该文件的这两部分资源一个不落地回收,回收方法为:

1、f.close() #回收操作系统级打开的文件
2、del f #回收应用程序级的变量
其中del f一定要发生在f.close()之后,否则就会导致操作系统打开的文件还没有关闭,白白占用资源,
而python自动的垃圾回收机制决定了我们无需考虑del f,这就要求我们,在操作完毕文件后,一定要记住f.close()


with关键字管理上下文:

#功能一:自动关闭文件句柄。
#功能二:一次性操作多个文件句柄。

with open('a.txt','w') as f: 
  pass 
with open('a.txt','r') as read_f,open('b.txt','w') as write_f: 
  data=read_f.read() 
  write_f.write(data)

威尼斯人线上娱乐, 4.2文件编码

f=open(...)是由操作系统打开文件,那么如果我们没有为open指定编码,那么打开文件的默认编码很明显是操作系统说了算了,
操作系统会用自己的默认编码去打开文件,在windows下是gbk,在linux下是utf-8。
若要保证不乱码,文件以什么方式存的,就要以什么方式打开。
f=open('a.txt','r',encoding='utf-8')

 4.3文本的打开格局

打开主要分两种类型:
文本文件:这些文件包含了文本,包括字母、数字、标点符号和一些特殊字符,如换行符。
二进制文件:这些文件不包含文本,它们可能包含音乐、图片或其他类型的数据。这些文件中不包含文件,所以没有行,不存在换行符。
      (间接性说明不能对二进制文件使用readline()或者readliners())
       # 大多数情况下,若果需要使用二进制文件,就要通过pygame或者其他一些模块来加载文件

#1. 打开文本文件模式有:
  • r,
    只读模式【私下认可形式,文件必须存在,不存在则抛出格外】
  • w,
    只写形式【不可读;不存在则开创;存在则清空内容】
  • x,
    只写方式【不可读;不存在则开创,存在则报错】
  • a,
    追加形式【可读;不设有则创建;存在则只扩展内容】

#2. 对于非文本文件(二进制文件),我们只能使用b模式,"b"表示以字节的方式操作
(而所有文件也都是以字节的形式存储的,使用这种模式无需考虑文本文件的字符编码、图片文件的jgp格式、视频文件的avi格式)
rb或r+b,读写
wb或w+b,写读
ab或a+b,写读
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码

#3,‘+’模式(就是增加了一个功能)
r+, 先读,后追加。一定要先读后写
w+, 先写,后读(这个其实作用并不大,写完光标已经到最后,打印啥都没有,必须还需把光标移到前面才能读)
a+, 追加,再读(这个也一样)

练习,利用b模式,编写一个cp工具,要求如下:
既可以拷贝文本又可以拷贝视频,图片等文件

1 # b模式
2 f=open('1.jpg','rb')
3 data=f.read()
4 # print(data)
5 f=open('2.jpg','wb')
6 f.write(data)
7 print(data) 

一,用python创设2个新文件,内容是0到9的平头,每一种数字占一行

f = open('f.txt','w')
for i in range(0,10):
    f.write(str(i)+'\n')

二,文件内容充实,从0到9的13个随机整数,每种数字占用一行

import random
f = open('a.txt', 'a')
for i in range(10):    #这一步作用在于让下面程序运行十次
    f.write(str(random.randint(0, 10)))
    f.write('\n')    # 这一步其实也可以和上一步合并起来
f.close()

③ 、文件内容充实,从0到9的人身自由整数,
十二个数字一行,共10行

import random
f = open('f.txt','a')
for i in range(0,10):
    for i in range(0,10):
        f.write(str(random.randint(0,9)))
    f.write('\n')
f.close()

 逐行读取文件内容的三种格局:

for line in open('f.txt'):
    print(line)

or:
f =open('f.txt','r')
lines =f.readlines()  
for i in lines:
    print(i)

4.4文书操作方法

4.4.0常用操作方法

 read(3):

  1.
文本打开格局为文本情势时,代表读取三个字符

  2.
文本打开药方式为b情势时,代表读取二个字节

其余的文本内光标移动都以以字节为单位的如:seek,tell,truncate

注意:

  1.
seek()是以bytes为单位活动的,遵照字节调整光标地方

  2.tell()是按字节读取光标地方

  3.
truncate是截断文件,所以文件的打开药情势必须可写,可是无法用w或w+等格局打开,因为那样间接清空文件了,所以truncate要在r+或a或a+等情势下测试效果。

1 import time
2 with open('test.txt','rb') as f:
3     f.seek(0,2)
4     while True:
5         line=f.readline()
6         if line:
7             print(line.decode('utf-8'))
8         else:
9             time.sleep(0.2)

4.4.1 序列化

  程序运营中,全部变量都是在内部存款和储蓄器里面,能够随时修改变量,不过假设程序结束,变量所占据的内存就会被操作系统全体回收。修改后的变量假若没有储存到磁盘上,下次开拓又会发轫化成原来的值。

  变量从内部存款和储蓄器中变成可存储或可传输的进度称之为体系化(python中称之为packling)。种类化之后,就能够把内容写入磁盘,或透过互连网传输到任何磁盘上

4.4.2 在文件中保存内容(文件的种类化)

》》》》》》》》模块链接

此处一般会用到pickle模块(它不得不用来python,不一样的python版本之间只怕也不般配)

要么json模块(能够在区别的编制程序语言之间传递对象,而且json表示出来就是五个字符串,能够被有着语言替代)

eval内置函数:

  该函数能够把字符串当作可进行代码运转,然则安全性较差,后边推荐应用hasattr映射

x, y, z = 43, 44, 45
S = 'splm'
D = {'a': 1, 'b': 2}
L = [1, 2, 3]

F = open('file.txt', 'w')
F.write(S + '\n')
F.write('%s%s%s\n' % (x, y, x))
F.write(str(L) + '$' + str(D) + '\n')
F.close()    
# 通过以上步骤将内容写入文件中

chars = open('file.txt')    # 打开文件
line = chars.readline()    # 只读取一行
line_two = chars.readline()
line_three = chars.readline()
print(line_three)
parts = line_three.split('$')  
print(parts)     #   ['[1, 2, 3]', "{'a': 1, 'b': 2}\n"]
print(eval(parts[1]))    #通过eval函数执行程序代码

temp = [eval(i) for i in parts]
print(temp)    #  [[1, 2, 3], {'a': 1, 'b': 2}]

 4.5 文件补充

威尼斯人线上娱乐 21

威尼斯人线上娱乐 22

4.6文书的改动(利用os模块)

列出当前目录下的有着目录:

[x for x
in os.listdir(‘.’) if os.path.isdir(x)]

要列出装有的
.py 文件,也只需一行代码:

[x for x
in os.listdir(‘.’) if os.path.isfile(x) and
os.path.splitext(x)[1]==’.py’]

4.7 文件删除和重命名

文件的数目是存放在于硬盘上的,由此只设有覆盖、不存在修改这么一说,我们一直看看的改动文件,都以效仿出来的法力,修改文件具体分为以下几步:

1,将原文件读取到内存。
2,在内存中进行修改,形成新的内容。
3,将新的字符串写入新文件。
4,将原文件删除。
5,将新文件重命名成原文件。

Python的os模块提供了帮您执行文书处理操作的艺术,比如重命名和删除文件。要动用那么些模块,你无法不早先入它,然后才得以调用相关的各类成效。

重命名和删除文件:

import os
#重命名文件,旧文件名f.txt,新文件名file.txt
os.rename('f.txt','file.txt')

import os
os.remove('stdout.txt') 

 

格局一:将硬盘存放的该文件的内容总体加载到内部存款和储蓄器,在内部存款和储蓄器中是足以修改的,修改达成后,再由内部存款和储蓄器覆盖到硬盘(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('alex','SB')      #在内存中完成修改
  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('alex','SB')
    write_f.write(line)

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

例题:

有如下文件:


alex是老男孩python发起人,创设人。

alex其实是人妖。

谁说alex是sb?

你们真逗,alex再牛逼,也掩饰不住资深屌丝的风韵。


将文件中负有的alex都替换来大写的SB。

威尼斯人线上娱乐 23威尼斯人线上娱乐 24

import os
with open('a.txt', mode='r', encoding='gbk') as f,\
    open('b.txt', mode='w', encoding='gbk') as f1:
    for i in f:
        if 'alex' in i:
            a = i.replace('alex', 'SB')
            f1.write(a)
os.remove('a.txt')
os.rename('b.txt', 'a.txt')

覆盖的研讨

文件a.txt内容:每一行内容分别为商品名字,价钱,个数。

apple
10 3

tesla 100000
1

mac 3000
2

lenovo 30000
3

chicken 10
3

由此代码,将其创设成那种数据类型:[{‘name’:’apple’,’price’:10,’amount’:3},{‘name’:’tesla’,’price’:1000000,’amount’:1}……] 

威尼斯人线上娱乐 25威尼斯人线上娱乐 26

lis = []
sums = 0
f = open('a.txt', mode='r', encoding='utf-8')
for i in f:
    s = i.strip().split(' ')
    a = dict([('name', s[0]), ('price', int(s[1])), ('amount', int(s[2]))])
    lis.append(a)
    sums += int(s[1])*int(s[2])
f.close()
print(lis)

low way

威尼斯人线上娱乐 27威尼斯人线上娱乐 28

with open('a.txt',encoding='utf-8') as f1:
    for i in f1:
        l2 = i.strip().split()           #l2 = [apple,10,3,2004]
        dic = {}
        for j in range(len(l2)):
            dic[name_list[j]] = l2[j]    # dic[name] = apple dic[price] = 10
        l1.append(dic)
print(l1)

珍重编制程序思想

文本a1.txt剧情:每一行内容分别为货品名字,价钱,个数。
文件内容:

name:apple
price:10 amount:3 year:2012
name:tesla price:100000 amount:1 year:2013

通过代码,将其创设成那种数据类型:
[{‘name’:’apple’,’price’:10,’amount’:3},
{‘name’:’tesla’,’price’:1000000,’amount’:1}……]

威尼斯人线上娱乐 29威尼斯人线上娱乐 30

with open('a1.txt', mode='r', encoding='gbk') as f:
    for i in f:
        a = i.replace(':', ' ').strip()
        b = a.split(' ')
        dic = dict([(b[0], b[1]), (b[2], int(b[3])), (b[4],int(b[5]))])
        print(dic)

low way

威尼斯人线上娱乐 31威尼斯人线上娱乐 32

l1 = []
with open('a1.txt',encoding='utf-8') as f1:
    for i in f1:
        li = i.strip().split()
        dic = {}
        for j in li:
            l2 = j.strip().split(':')
            dic[l2[0]] = l2[1]
        l1.append(dic)
print(l1)

名师方法

文件a2.txt内容:每一行内容分别为货品名字,价钱,个数。

文本内容:
序号     部门      人数      平均年龄      备注
1       python    30         26         单身狗
2       Linux     26         30         没对象
3       运营部     20         24         女生多
通过代码,将其创设成那种数据类型:
[{‘序号’:’1′,’部门’:Python,’人数’:30,’平均年龄’:26,’备注’:’单身狗’},
……]

威尼斯人线上娱乐 33威尼斯人线上娱乐 34

d = []
with open('a2.txt', mode='r', encoding='gbk')as f:
    s = f.readline()
    data = s.strip().split(' ')
    b = [x for x in data if x != '']
    for i in f:
        data1 = i.strip().split(' ')
        c = [x for x in data1 if x != '']
        dic = dict([(b[0], int(c[0])), (b[1], c[1]), (b[2], int(c[2])), (b[3], int(c[3])), (b[4], c[4])])
        d.append(dic)
print(d)

my idea

威尼斯人线上娱乐 35威尼斯人线上娱乐 36

d = []
with open('a2.txt', mode='r', encoding='gbk')as f:
    lis = f.readline().strip().split()
    for i in f:
        b = i.strip().split()
        dic = dict([(lis[0], b[0]),(lis[1], b[1]),(lis[2], b[2]),(lis[3], b[3]),(lis[4], b[4])])
        d.append(dic)
print(d)

改造后的,看看和下面何地分裂了

威尼斯人线上娱乐 37威尼斯人线上娱乐 38

lis = []
with open('message.txt',encoding='gbk') as f:
    lis1 = f.readline().strip().split(',')
    for j in f:
        dic = {}
        lis2 = j.strip().split(',')
        for i in range(len(lis1)):
            dic[lis1[i]] = lis2[i]
        lis.append(dic)
    print(lis)

和谐为何想不到,利用len的不二法门

 

 

 


相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图