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 "\nEnter lines('.' by itself to quit).\n"

#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!'

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM