栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python中的用for,while循环遍历文件实例

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python中的用for,while循环遍历文件实例

使用for循环遍历文件

打开文件

open

     r:以读模式打开

    w:以写模式打开

    a:以追加模式打开

    r+:以读写模式打开

    w+:以读写模式打开(参见w)

    a+:以读写模式打开(参见a)

    rb:以二进制读模式打开

    wb:以二进制写模式打开(参见w)

    ab:以二进制追加模式打开(参见a)

    rb+:以二进制读写模式打开(参见r+)

    wb+:以二进制读写模式打开(参见w+)

    ab+:以二进制读写模式打开(参见a+)


查看帮助:

    open(...)

    open(name[, mode[, buffering]]) -> file object

    Open a file using the file() type, returns a file object.  This is the

    preferred way to open a file.  See file.__doc__ for further information.

    (END)...skipping...


    [root@localhost ~]# cat /tmp/1.txt

    1111

    [root@localhost ~]#

只读方式打开:

    In [26]: open('/tmp/1.txt')

    Out[26]:

    In [27]: fd = open('/tmp/1.txt')

    In [28]: fd

    Out[28]:

    In [29]: type(fd)

    Out[29]: file

以写方式打开:

    In [34]: fd = open('/tmp/1.txt','w')

    In [35]: fd.write('2222n')

    In [36]: fd.close()

    [root@localhost ~]# cat /tmp/1.txt

    2222

    [root@localhost ~]#

以追加方式打开:

    In [34]: fd = open('/tmp/1.txt','a')

    In [35]: fd.write('3333n')

    In [36]: fd.close()

    [root@localhost ~]# cat /tmp/1.txt

    2222

    3333

    [root@localhost ~]#

    

read():

    In [41]: fd.read()

    Out[41]: '2222n3333n'

    In [42]: fd.read()

    Out[42]: ''

    In [49]: fd.readline()

    Out[49]: '2222n'

    In [50]: fd.readline()

    Out[50]: '3333n'

    In [51]: fd.readline()

    Out[51]: ''

    In [52]:


read()  和readline()返回的是字符串:

readlines()返回的是列表:

    in [52]: fd = open('/tmp/1.txt')

    In [53]: fd.readlines()

    Out[53]: ['2222n', '3333n']

脚本:

    #!/usr/bin/python

    fd = open('/tmp/1.txt')

    for line in fd:

    print line,

    fd.close()


    [root@localhost 20171228]# python read_file.py

    2222

    3333

    [root@localhost 20171228]#

使用while循环遍历文件

脚本:

    #!/usr/bin/python

    fd = open('/tmp/1.txt')

    while True:

    line = fd.readline()

    if not line:

    break

    print line,

    fd.close()

    

    [root@localhost 20171228]# python read_fi_while.py

    2222

    3333

    [root@localhost 20171228]#


with open打开文件 :

    #!/usr/bin/python

    with open('/tmp/1.txt') as fd:

    while True:

    line = fd.readline()

    if not line:

    break

    print line,

    

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/222829.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号