zoukankan      html  css  js  c++  java
  • python 读取文件函数

    python 读取文件函数

    觉得有用的话,欢迎一起讨论相互学习~


    我的微博我的github我的B站

    感谢莫烦老师
    详情

    读取文件内容 file.read()

    • 使用 file.read() 能够读取到文本的所有内容.
    file= open('my file.txt','r')
    content=file.read()  
    print(content)
    
    """"
    This is my first test.
    This is the second line.
    This the third line.
    This is appended file.    
    """"
    

    按行读取 file.readline()

    • 如果想在文本中一行行的读取文本, 可以使用 file.readline(), file.readline() 读取的内容和你使用的次数有关, 使用第二次的时候, 读取到的是文本的第二行, 并可以以此类推:
    file= open('my file.txt','r')
    content=file.readline()  # 读取第一行
    print(content)
    
    """"
    This is my first test.
    """"
    
    second_read_time=file.readline()  # 读取第二行
    print(second_read_time)
    
    """
    This is the second line.
    """
    

    读取所有行 file.readlines()

    • 如果想要读取所有行, 并可以使用像 for 一样的迭代器迭代这些行结果, 我们可以使用 file.readlines(), 将每一行的结果存储在 list 中, 方便以后迭代.
    file= open('my file.txt','r')
    content=file.readlines() # python_list 形式
    print(content)
    
    """"
    ['This is my first test.
    ', 'This is the second line.
    ', 'This the third line.
    ', 'This is appended file.']
    """"
    
    # 之后如果使用 for 来迭代输出:
    for item in content:
        print(item)
    
    """
    This is my first test.
    
    This is the second line.
    
    This the third line.
    
    This is appended file.
    """
    
  • 相关阅读:
    selenium 下载百度音乐并验证
    selenium web driver 实现截图功能
    selenium web driver 使用JS修改input属性
    .net测试学习--理解.net测试选项
    试水STF(smartphone test farm)
    The difference between QA, QC, and Test Engineering
    selenium 3.0 beta2 初体验
    Gson解析纯Json数组
    Android带图片的Toast(自定义Toast)
    Android issues
  • 原文地址:https://www.cnblogs.com/cloud-ken/p/12634130.html
Copyright © 2011-2022 走看看