zoukankan      html  css  js  c++  java
  • python从文件中读取数据

     一、读取整个文件

    learnFile.py

    绝对路径

    # coding=UTF-8
    import sys
    reload(sys)
    with open(r'C:\Users\zhujiachun\Desktop\test_text.txt','r') as file_object:
            contents = file_object.read()
            print contents

    learnFile.py所在的目录中查找test_text.txt 并打开

    
    
    # coding=UTF-8
    import sys
    reload(sys)
    with open('test_text.txt') as file_object:
            contents = file_object.read()
            print contents

    with open():在不需要访问文件后将其关闭
    也可以用open(),close()。但如果程序存在bug,可能导致close()不执行,文件不关闭。
    因此推荐用with open()方法

    结果:

     出现IOError: [Errno 22] invalid mode ('r') or filename:解决方法:

    如果你要是对文件进行写入操作应该这样
    f=open(r‘c:\fenxi.txt’,'w')
    如果是只是读取:
    f=open(r‘c:\fenxi.txt’,'r')

    删除读取文件显示内容末尾空行:

    read()到达文件末尾会返回一个空字符串,显示出来就是一个空行

    可使用rstrip():

    删除空格用strip()

    # coding=UTF-8
    import sys
    reload(sys)
    with open('test_text.txt') as file_object:
            contents = file_object.read()
            print contents.rstrip()

    二、逐行读取

    使用for循环读取每一行

    # coding=UTF-8
    
    with open('test_text.txt') as file_object:
           for line in file_object:
               print line.rstrip()

    储存在列表中读取

    # coding=UTF-8
    
    with open('test_text.txt') as file_object:
        lines = file_object.readlines()
        for line in lines:
             print line.rstrip()
  • 相关阅读:
    LNOI2014LCA(树链剖分+离线操作+前缀和)
    CDQ分治与整体二分学习笔记
    BJWC2018上学路线
    NOIP2013火柴排队
    SHOI2008仙人掌图(tarjan+dp)
    作诗(分块)
    COGS314. [NOI2004] 郁闷的出纳员
    bzoj 1691: [Usaco2007 Dec]挑剔的美食家
    COGS1533.[HNOI2002]营业额统计
    bzoj1208: [HNOI2004]宠物收养所
  • 原文地址:https://www.cnblogs.com/erchun/p/11766173.html
Copyright © 2011-2022 走看看