美文网首页
遍历文件

遍历文件

作者: C1awn_ | 来源:发表于2017-12-28 15:35 被阅读0次

    1. for循环遍历文件

    1. 打开文件open

    • open
      r:以读方式打开
      w :以写方式打开
      a :以追加模式
      r+ :以读写模式打开
      w+:以读写模式打开 (参见 w )
      a+:以读写模式打开 (参见 a )
      rb:以二进制读模式打开
      wb:以二进制写模式打开 (参见 w )
      ab:以二进制追加模式打开 (参见 a )
      rb+:以二进制读写模式打开 (参见 r+ )
      wb+:以二进制读写模式打开 (参见 w+ )
      ab+: 以二进制读写模式打开 (参见 a+)
    In [19]: fd = open('/tmp/tmp.txt') #/tmp/tmp.txt为新建空文件
    In [21]: type(fd)
    Out[21]: file
    

    这是打开文件

    In [22]: fd.
    fd.close       fd.fileno      fd.name        fd.readinto    fd.softspace   fd.writelines  
    fd.closed      fd.flush       fd.newlines    fd.readline    fd.tell        fd.xreadlines  
    fd.encoding    fd.isatty      fd.next        fd.readlines   fd.truncate    
    fd.errors      fd.mode        fd.read        fd.seek        fd.write       
    
    In [22]: fd.clo
    fd.close   fd.closed  
    
    In [22]: fd.close()
    
    • fd.closed关闭文件
    In [23]: fd = open('/tmp/tmp.txt','w')  #以W+
    
    In [24]: fd.wr
    fd.write       fd.writelines  
    
    In [24]: fd.write('aaa')  
    
    [root@t1 ~]# cat /tmp/tmp.txt
    [root@t1 ~]# 
    [root@t1 ~]# 
    
    
    In [25]: fd.clo
    fd.close   fd.closed  
    
    In [25]: fd.close()
    
    • fd.write()写入文件
    In [2]: fd.write('123\n')    #写入字符串123
    In [4]: fd.close()    
    [root@t1 ~]# cat /tmp/tmp.txt
    123
    
    • open以append方式打开
    In [5]: fd = open('/tmp/tmp.txt','a')
    
    In [6]: fd.write('456\n')
    
    In [7]: fd.clo
    fd.close   fd.closed  
    
    In [7]: fd.close()
    [root@t1 ~]# cat /tmp/tmp.txt
    123
    456
    

    2. 读文件read

    • fd.read()--步进读,返回字符串
    In [9]: fd = open('/tmp/tmp.txt')
    
    In [10]: fd.read()          #read()什么都不加会读出所有内容
    Out[10]: '123\n456\n'
    
    In [11]: fd.read()        #再次读的时候已经没有内容,所以是空
    Out[11]: ''
    

    对比下面的:

    In [13]: fd = open('/tmp/tmp.txt')
    
    In [14]: fd.read(2)        #读前面2个
    Out[14]: '12'
    
    In [15]: fd.read()        #继续读剩下的
    Out[15]: '3\n456\n'
    
    • fd.readline()--读行,返回字符串
    In [16]: fd = open('/tmp/tmp.txt')
    
    In [17]: fd.readline()        #读第一行
    Out[17]: '123\n'
    
    In [18]: fd.readline()        #读第二行
    Out[18]: '456\n'
    
    • fd.readlines()--读所有行,并返回list
    In [19]: fd = open('/tmp/tmp.txt')
    
    In [20]:  fd.readlines()
    Out[20]: ['123\n', '456\n']
    
    • 脚本读文件举例
    [root@t1 py]# cat 1.py
    #!/usr/bin/python
    # -*- coding:utf8 -*-
    # author: chawn
    # date:
    fd = open('/tmp/tmp.txt')
    for line in fd.readlines():  
        print line ,        #注意,没有的话print自带一个换行符
    fd.close()        #读完文件最好手动关闭,虽然执行完程序系统会关闭
    

    执行结果和cat一样

    [root@t1 py]# python 1.py
    123
    456
    

    for line in fd.readlines()读取所有行会占用很大内存,如果这个文件很大的话
    建议将for line in fd.readlines()改写成for line in fd,这样会一行一行读,不会出现list

    • fd.next
    In [2]: fd = open('/tmp/tmp.txt')
    In [4]: fd.next()
    Out[4]: '123\n'
    
    In [5]: fd.next()
    Out[5]: '456\n'
    

    2. while遍历文件

    #!/usr/bin/python
    # -*- coding:utf8 -*-
    # author: chawn
    # date:
    fd = open('/tmp/tmp.txt')
    while 1:          #死循环
        line = fd.readline()
        if not line:   #如果line到了空行,not line就是真
            break
        print line ,
    fd.close()
    

    执行结果:

    [root@t1 py]# python 1.py
    123
    456
    
    • with open用上的话,可以不用手动关闭文件。而且with是关键字
      改一下上面的代码
    #!/usr/bin/python
    # -*- coding:utf8 -*-
    # author: chawn
    # date:
    with open('/tmp/tmp.txt') as fd:
        while 1:
            line = fd.readline()
            if not line:
                break
            print line ,
    

    注意with后的:,和下面的缩进

    3. 练习

    习题

    1. 现有一个文件test.txt ,内容如下:
      1234efgh
      abcd5678
      要求读出文件内容,对内容的顺序进行编辑,然后重新写入到文件,使其为如下形式
      12345678
      abcdefgh
      注意事项:使用pycharm的同学在调试程序时,如果程序对文件进行了操作,然后手动修改了文件,则要在pycharm中,程序所在的目录上点击右键,选择clean python compiled files,否则可能会报错
    1. 将上周五生成的dict3,排序后写入到文件dict.txt中,要求格式为
      A 65
      B 66
      C 67
      ...
      x 120
      y 121
      z 122
    1. 解答:
    list1 = list()
    
    with open('test.txt','r') as f:
    
        for i in f.readlines():
    
           list1.append(i)
    
        line1 = list1[0][0:4] + list1[1][4:]
    
        line2 = list1[1][0:4] + list1[0][4:]
    
        with open('test.txt','w') as fd:
    
            fd.write(line1)
    
            fd.write(line2)
    
    1. 解答
    import string
    
    dict1 = {'a': 97, 'c': 99, 'b': 98, 'e': 101, 'd': 100, 'g': 103, 'f': 102, 'i': 105, 'h': 104, 'k': 107, 'j': 106, 'm': 109, 'l': 108, 'o': 96, 'n': 110, 'q': 113, 'p': 112, 's': 115, 'r': 114, 'u': 117, 't': 116, 'w': 119, 'v': 118, 'y': 121, 'x': 120, 'z': 122}
    
    dict1['o'] = 111
    
    dict1 = sorted(dict1.items(), key=lambda a:a[0])
    
    dict1 = dict(dict1)
    
    dict2 = dict(zip(string.ascii_uppercase,range(65,92)))
    
    dict3 = dict(dict1, **dict2)
    
    dict3 = sorted(dict3.items(), key=lambda a:a[0])
    
    with open(r'D:\dict.txt','w') as f:
    
        for k,v in dict3:
    
            f.write(k + ' ')
    
            f.write(str(v) + '\n')
    

    相关文章

      网友评论

          本文标题:遍历文件

          本文链接:https://www.haomeiwen.com/subject/rllvgxtx.html