zoukankan      html  css  js  c++  java
  • 老齐python-基础7(文件操作、迭代)

        在python3中,没有file这个内建类型了(python2中,file是默认类型)

    1、读文件

        创建文件,130.txt 并在里面输入

    learn python
    http://qiwsir.github.io
    qiwsir@gmail.com
    >>> f = open("130.txt")
    >>> dir(f)  #查看方法
    ['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 'readline', 'readlines', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'writelines']
    
    f = open("./codes/130.txt")  #当在上级目录时指定文件
    for line in f:
        print(line)

    2、创建文件

    >>> nf = open("txtfile.txt","w")  #创建txtfile.txt文件
    >>> nf.write("This is a new file")  #文件中添加一句话,并返回字符串长度
    18
    >>> nf.close()   #关闭打开的文件

        只读方式测试

    >>> f = open("txtfile.txt")
    >>> f
    <_io.TextIOWrapper name='txtfile.txt' mode='r' encoding='UTF-8'>
    >>> f = open("txtfile.txt","r")
    >>> f
    <_io.TextIOWrapper name='txtfile.txt' mode='r' encoding='UTF-8'>

        1)w 模式,以写方式打开文件,可向文件写入信息。如果文件存在则清空文件,再写新内容。

        2)a 模式,以追加模式打开文件(一打开文件,文件指针自动移到文件末尾),如果文件不存在则创建

           也可以用这种模式打开一个不存在的文件,即新建

    >>> fn = open("mdfile.md","a")
    >>> fn
    <_io.TextIOWrapper name='mdfile.md' mode='a' encoding='UTF-8'>
    >>> fn.write("python can helo you to be agreat programmer.")
    44
    >>> fn.close()

    3、使用with

         在对文件进行写入操作之后,都要执行file.close(),它的作用就是将文件关闭,同事也将内容保存在文件中。

         除了显示的操作关闭之外,还有另外一种方法with,更加pythonic

    >>> with open("mdfile.md","a") as f:
    ...     f.write("
    I am a Pythoner.")
    ...
    17

    4、文件的状态

        有时候要获取一个文件的状态(也成为属性),比如创建日期、修改日期、大小等。

    >>> import os
    >>> file_stat = os.stat("mdfile.md")  #使用os模块读取文件属性
    >>> file_stat
    os.stat_result(st_mode=33188, st_ino=8672850, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=61, st_atime=1505309783, st_mtime=1505309775, st_ctime=1505309775)
    >>> file_stat.st_ctime
    1505309775.0
    >>> import time    #使用time模块读取时间
    >>> time.localtime(file_stat.st_ctime)
    time.struct_time(tm_year=2017, tm_mon=9, tm_mday=13, tm_hour=21, tm_min=36, tm_sec=15, tm_wday=2, tm_yday=256, tm_isdst=0)

    5、read/readline/readlines

    >>> f = open("mdfile.md")  
    >>> f.read(12)  #读取前12个字符
    'python can h'
    >>> f.read()    #如果不指定就输出到EOF为止(End of file)
    'elo you to be agreat programmer.
    I am a Pythoner.'   #指针的原因没有读取前部分

        readline,逐行读取文件内容

    >>> f.readline()   #每执行一次读取一行
    'python can helo you to be agreat programmer.
    '
    >>> f.readline()
    'I am a Pythoner.'
    >>> f.readline()
    ''

        readlines,将文件各行读出来,放到一个列表中返回

    >>> f = open("mdfile.md")
    >>> f.readlines()
    ['python can helo you to be agreat programmer.
    ', 'I am a Pythoner.']
    >>> f = open("mdfile.md")
    >>> for line in f.readlines(): print(line)
    ...
    python can helo you to be agreat programmer.
    
    I am a Pythoner.
    >>> f = open("mdfile.md")
    >>> for line in f: print(line)   #看似相同其实不同,readlines已经在内存中生成列表
    ...
    python can helo you to be agreat programmer.
    
    I am a Pythoner.
    

     6、读很大的文件

    >>> import fileinput
    >>> for line in fileinput.input("you.md"): print(line,end='')
    ...
    You Raise Me Up
    When I am down 当我失意低落之时
    and, oh my soul, so weary; 我的精神,是那么疲倦不堪
    When troubles come 当烦恼困难袭来之际
    and my heart burdened be; 我的内心,是那么负担沉重
    Then, I am still 然而,我默默的伫立
    and wait here in the silence, 静静的等待
    Until you come 直到你的来临
    and sit awhile with me. 片刻地和我在一起

    7、seek

        读取文件,指针也随着运动,当读取结束时,这阵就移动了相应的位置。

    >>> f = open("you.md")
    >>> f.readline()
    'You Raise Me Up
    '
    >>> f.readline()
    'When I am down 当我失意低落之时
    '
    >>> f.tell()            #查看指针位置
    56
    >>> f.seek(0)        #重置指针位置
    0
    >>> f.readline()
    'You Raise Me Up
    '
    >>> f.tell()
    16
    >>> f.readline()
    'When I am down 当我失意低落之时
    '
    >>> f.seek(4)       #将指针移动到对应位置
    4
    >>> f.tell()
    4
    >>> f.readline()
    'Raise Me Up
    '

         指针特性:

             seek(offset[,whence])是这个函数的完整形式,以上我们省略了whence,在默认情况下都是以文件的开头为参照物进行移动的,即whence=0 whence,还可以有别的值,具体:

            1)默认值是0,表示从文件开头开始计算指针偏移的量(简称偏移量)

            2)当whence=1,表示从当前位置开始计算偏移量。

            3)当whence=2,表示相对文件末尾移动

    二、初识迭代

        循环(Loop),指的是在满足条件的情况下,重复执行同一段代码,如while语句。

        迭代(Iterate),指的是按照某种顺序诸葛访问对象(如列表)中的每一项,如for语句。

        递归(Recursion),指的是一个函数不断调用自身的行为,如著名的斐波那契数列。

        遍历(Traversal),指的是按照一定的规则访问树形结构中的每个节点,而且每个节点都只访问一次。for循环就是一种遍历。

  • 相关阅读:
    C++内置类型对象之间的转换
    快速排序
    面试题7:用两个栈实现队列
    面试题6:重建二叉树
    poj 3264(线段树)
    poj 3038
    poj 并查集
    poj 1270(toposort)
    poj 2503(字符串)
    poj 3687(拓扑排序)
  • 原文地址:https://www.cnblogs.com/Taj-Zhang/p/7518056.html
Copyright © 2011-2022 走看看