zoukankan      html  css  js  c++  java
  • python 简单的txt文件读写

    1 读取txt文件。跟c相比,python的文件读写简直是方便的可怕

      首先是读取文件

      首先获得文件名称,然后通过 open函数打开文件,通过for循环逐行读出文件内容

    #!python file by ninahao 10.30
    
    'readfile.py--read and display text file'
    
    #get filename
    fname=raw_input('enter file name:')
    print
    
    #attempt to open file for reading
    try:
        fobj=open(fname,'r')
    except IOError,e:
        print 'open file--',fname,'--error!:',e
    else:
        #display content to the screen
        for eachline in fobj:
            print eachline
    fobj.close()

    2 写入文件并保存,同理,新建一个文件,也是通过open函数。神奇。

    #!maketext.py
    'maketextfile.py--create text file'
    
    import os
    ls=os.linesep
    
    #get filename
    while True:
        fname=raw_input('enter file name : ')
        if os.path.exists(fname):
            print "ERROR: '%S' already exists" % fname
        else:
            break
    
    #get file content(text) lines
    all=[]
    print "
    Enter lines('.' by itself to quit).
    "
    
    #loop until user terminates input
    while True:
        entry=raw_input('>')
        if entry=='.':
            break;

          all.append(entry)

    ##write lines to file with proper line-ending
    fobj=open(fname,'w')
    fobj.writelines(['%s%s' % (x,ls) for x in all])
    fobj.close()
    print 'DONE!'

  • 相关阅读:
    斜率优化dp学习
    拓扑排序
    P2486 [SDOI2011]染色 区间合并+树链剖分(加深对线段树的理解)
    网络流24题!!!!
    费用流板子
    网络流dinic板子
    小花梨的数组
    C. 小花梨判连通
    splay树
    hdu4467 graph
  • 原文地址:https://www.cnblogs.com/superxuezhazha/p/6012771.html
Copyright © 2011-2022 走看看