电脑种类分为:硬件,操作系统,应用程序

一,文件操作基本流程。

处理器种类分为:总括机硬件,操作系统,应用程序三部分。

我们用python或其余语言编写的应用程序若想要把数据永久保存下来,要求求保存于硬盘中,那就提到到应用程序要操作硬件,举世盛名,应用程序是无力回天间接操作硬件的,那就用到了操作系统。操作系统把复杂的硬件操作封装成简单的接口给用户/应用程序使用,在那之中文件便是操作系统提要求应用程序来操作硬盘虚拟概念,用户或应用程序通过操作文件,可以将协调的数额永久保存下来。

有了文本的概念,我们无需再去考虑操作硬盘的底细,只必要关切操作文件的流水线:

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

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

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

 

归来目录页

一. 文书操作基本流程

电脑体系分为:总括机硬件,操作系统,应用程序三有个别。

咱俩用python或其它语言编写的应用程序若想要把数据永久保存下来,必须求保留于硬盘中,那就涉及到应用程序要操作硬件,家喻户晓,应用程序是不能够直接操作硬件的,那就用到了操作系统。操作系统把复杂的硬件操作封装成简单的接口给用户/应用程序使用,其汉语件正是操作系统提须求应用程序来操作硬盘虚拟概念,用户或应用程序通过操作文件,能够将本人的数目永久保存下去。

金沙注册送58,有了文本的定义,我们无需再去考虑操作硬盘的底细,只要求关爱操作文件的流水线:

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

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

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

硬件:意在运维软件发生的授命。硬件蕴含CPU,内部存款和储蓄器,硬盘

闭馆文件的注意事项:

金沙注册送58 1金沙注册送58 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的指令集中的1个子集,该子集不包涵操作硬件的指令集)

 四,文件操作方法。

文件的开辟情势

文件句柄 = 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, 写读【可写,可读】

四. 文件操作方法

金沙注册送58 3 

4.1常用操作方法。

read(3):

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

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

任何的文书内光标移动皆以以字节为单位的如:seek,tell,truncate

注意:

  1.
seek有三种运动格局0,1,2,个中1和2亟须在b方式下展开,但无论哪一类情势,都以以bytes为单位活动的

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

文本操作方法

4.1常用操作方法

read(3):

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

  2. 文本打开药格局为b方式时,代表读取三个字节

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

注意:

  1.
seek有三种运动格局0,1,2,在那之中1和2亟须在b方式下展开,但不管哪类方式,都以以bytes为单位活动的

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

至于文件:

4.2有着操作方法。

金沙注册送58 4金沙注册送58 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

金沙注册送58 6金沙注册送58 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存有操作方法

金沙注册送58 8金沙注册送58 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

金沙注册送58 10金沙注册送58 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

  • 文件能够储存分歧门类的音信,三个文书能够分包文本,图片,摄像,计算机程序等内容。
  • 电脑上硬盘上富有的始末都以以文件的花样储存。程序正是由3个依然四个文本构成的。
  • 文本对象是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') 

 

不无操作方法。

金沙注册送58 12金沙注册送58 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

金沙注册送58 14金沙注册送58 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++等编辑器)

金沙注册送58 16金沙注册送58 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')   #将新建的文件重命名为原文件

方法一

python之文件操作,文件操作。办法二:将硬盘存放的该文件的始末一行一行地读入内部存款和储蓄器,修改完成就写入新文件,最终用新文件覆盖源文件

金沙注册送58 18金沙注册送58 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)

金沙注册送58 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创造贰个新文件,内容是0到9的整数,各样数字占一行

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

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

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的任意整数,
1三个数字一行,共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.
文件打开药格局为文本形式时,代表读取3个字符

  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 文件补充

金沙注册送58 21

金沙注册送58 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。

金沙注册送58 23金沙注册送58 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}……] 

金沙注册送58 25金沙注册送58 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

金沙注册送58 27金沙注册送58 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}……]

金沙注册送58 29金沙注册送58 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

金沙注册送58 31金沙注册送58 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,’备注’:’单身狗’},
……]

金沙注册送58 33金沙注册送58 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

金沙注册送58 35金沙注册送58 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)

改建后的,看看和方面哪儿分化了

金沙注册送58 37金沙注册送58 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地图