python 简单的txt文件读写

时间:2022-12-20 13:13:43

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