首页 > 编程语言 > 详细

python 简单的txt文件读写

时间:2016-10-30 13:32:27      阅读:210      评论:0      收藏:0      [点我收藏+]

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

 

python 简单的txt文件读写

原文:http://www.cnblogs.com/superxuezhazha/p/6012771.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!