zoukankan      html  css  js  c++  java
  • Python三种读取txt文件方式

    简单介绍

    1.按行读取方式readline()

    readline()每次读取文件中的一行,需要使用永真表达式循环读取文件。但当文件指针移动到文件的末尾时,依然使用readline()读取文件将出现错误。因此程序中需要添加1个判断语句,判断文件指针是否移动到文件的尾部,并且通过该语句中断循环。

    2.多行读取方式readlines()

    使用readlines()读取文件,需要通过循环访问readlines()返回列表中的元素。函数readlines()可一次性读取文件中多行数据。

    3.一次性读取方式read()读取文件最简单的方法是使用read(),read()将从文件中一次性读出所有内容,并赋值给1个字符串变量。

    代码:

    # -*- coding: utf-8 -*-

    file =open('/Users/april_chou/Desktop/WorkSpace/Selenium/seleniumTest/test.txt','r')

    context = file.read()

    print('read格式:')

    print(context)

    file.close()

    print()

    file =open('/Users/april_chou/Desktop/WorkSpace/Selenium/seleniumTest/test.txt','r')

    context = file.readlines()

    contextLines =''

    for i in context:

        contextLines = contextLines + i

    print('readlines格式:')

    print(contextLines)

    file.close()

    print()

    file =open('/Users/april_chou/Desktop/WorkSpace/Selenium/seleniumTest/test.txt','r')

    contextLines =''

    while True:

        context = file.readline()

        contextLines = contextLines + context

        if len(context) ==0:

        break

    print('readline格式:')

    print(contextLines)

    file.close()

    结果:

    read格式:

    hello world

    hello China

    readlines格式:

    hello world

    hello China

    readline格式:

    hello world

    hello China

  • 相关阅读:
    如何说明白代码评审
    面试感悟----一名3年工作经验的程序员应该具备的技能(转载自@五月的仓颉)
    根据ip地址从第三方接口获取详细的地理位置
    linux安装telnet遇到的问题
    redis脑图
    数据库相关面试题
    logback系列一:名词解释
    java并发编程系列一、多线程
    logback系列二:logback在项目中的应用
    rocketmq特性(features)
  • 原文地址:https://www.cnblogs.com/April-Chou-HelloWorld/p/8833874.html
Copyright © 2011-2022 走看看