今天继续码~python的文件访问~

来源:互联网 发布:js移除元素的属性值 编辑:程序博客网 时间:2024/06/07 06:50

为什么...昨天保存的博客不见了...难道是审核未通过嘛?也不告诉我...

进入正题吧~

首先是文件的写入:

诶,重复写昨天的东西,好烦好烦好烦。。。

import os#不同系统下的换行符ls = os.linesep#要求输入文件名,并检查文件是否重名while True:    fname = raw_input("Hi,let me know the name of the New file:")    if os.path.exists(fname):        print "ERROR,'%s' already exists!Please name the file again~" % fname    else:        breakall = []print "\n Enter lines ('.' by itself to quit).\n"#输入文件内的每一行while True:    entry = raw_input('>> ')    if entry == '.':        break    else:        all.append(entry)#写入文件,并关闭文件fobj = open(fname, 'w')fobj.writelines(["%s%s" % (x,ls) for x in all])fobj.close()print "Done!Tada!!"
上述代码的输出结果为:

>>> Hi,let me know the name of the New file:spy Enter lines ('.' by itself to quit).>> 12345>> 67890>> .Done!Tada!!>>> 


接下来是文件的输出:

filename = raw_input("Enter the filename that you want to read:")printtry:    fobj2 = open(filename, 'r')except IOError,e:    print "***Bibibi,Sorry, file open ERROR:",eelse:    for eachLine in fobj2:        print ">> ",eachLine,    fobj2.close()        print "DONE!Tada!!"

运行结果:

>>> Enter the filename that you want to read:test.py>>  str1 = "abcdef">>  print str1[::-1]>>  print str1[::-2]>>  list1 = [123, "xyz",123.123,'abc']>>  print list1[::-1]>>  >>  print id(str1)>>  print id(list1)>>   DONE!Tada!!>>> 




0 0
原创粉丝点击