首页 > 代码库 > python 简单的txt文件读写

python 简单的txt文件读写

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

  首先是读取文件

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

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

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

#!maketext.pymaketextfile.py--create text fileimport osls=os.linesep#get filenamewhile True:    fname=raw_input(enter file name : )    if os.path.exists(fname):        print "ERROR: ‘%S‘ already exists" % fname    else:        break#get file content(text) linesall=[]print "\nEnter lines(‘.‘ by itself to quit).\n"#loop until user terminates inputwhile 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!‘

 

python 简单的txt文件读写