• python 读取和输出到txt文件


    这篇文章主要介绍了python读取和输出到txt,文中通过示例代码介绍的非常详细,

     

    读取txt的数据和把数据保存到txt中是经常要用到的,下面我就总结一下。

    读txt文件

    python常用的读取文件函数有三种read()、readline()、readlines()

    以读取上述txt为例,我们一起来看一下三者的区别

    read() 一次性读全部内容

    read() #一次性读取文本中全部的内容,以字符串的形式返回结果

    1
    2
    3
    with open("test.txt", "r") as f:  #打开文件
      data = f.read()  #读取文件
      print(data)

    readline() 读取第一行内容

    readline() #只读取文本第一行的内容,以字符串的形式返回结果

    1
    2
    3
    with open("test.txt", "r") as f:
      data = f.readline()
      print(data)

    readlines() 列表

    readlines() #读取文本所有内容,并且以数列的格式返回结果,一般配合for in使用

    1
    2
    3
    with open("test.txt", "r") as f:
      data = f.readlines()
      print(data)

    可见readlines会读到换行符,我们可以用如下方法去除

    1
    2
    3
    4
    with open("test.txt", "r") as f:
      for line in f.readlines():
        line = line.strip(' ') #去掉列表中每一个元素的换行符
        print(line)

    写txt文件

    write

    1
    2
    with open("test.txt","w") as f:
        f.write("这是个测试!") #这句话自带文件关闭功能,不需要再写f.close()

    print到文件中

    1
    2
    3
    data=open("D:data.txt",'w+')
    print('这是个测试',file=data)
    data.close()

    读写的模式

    读写文件的时候有不同的模式,下面来总结一下:

    输出文件其它方法

           (1) 直接重定向,Python a.py >>a.txt

           (2)doc = open('out.txt','w') print(data_dict,file=doc) doc.close()

            (3)

    #coding:utf8

    import os

    def readFile(filename):

         file = os.open(filename,'rb')

               data=file.readlines()

               file.close()

              return data

    def writeFile(filename,data):

          file= os.open(filename,'wb')

                file.write(data)

                file.close()

               print 'File had been writed Succed!'


    if __name__=="__main__":

        sourcefile = r'./b.py'

              outputfile = r'./target.txt'

              writeFile(outputfile,readFile(sourcefile))

              print 'end!'

  • 相关阅读:
    ArcGIS for Android地图控件的5大常见操作
    adb开启不了解决方案
    Eclipse中通过Android模拟器调用OpenGL ES2.0函数操作步骤
    解决 Your project contains error(s),please fix them before running your application问题
    二路归并算法实现
    字符串全排列
    python连接MySQL
    .net常考面试题
    win7 web开发遇到的问题-由于权限不足而无法读取配置文件,无法访问请求的页面
    int.Parse()与int.TryParse()
  • 原文地址:https://www.cnblogs.com/tonyxiao/p/14435460.html
Copyright © 2020-2023  润新知