Python 文件的读写

001:读取文件:

>>> xxx = open("D:\\Python\\test.txt")
>>> print xxx.readlines()

['This is line #1\n', 'This is line #2\n', 'This is line #3\n', 'END']
>>> xxx = file("D:\\Python\\test.txt","rb")
>>> print xxx.readlines()

['This is line #1\n', 'This is line #2\n', 'This is line #3\n', 'END']
>>> xxx = file("d:\\python\\test.txt",'r')
>>> a = xxx.read()
>>> print a

['This is line #1\n', 'This is line #2\n', 'This is line #3\n', 'END']


当执行完之后,再次想执行 print xxx.readlines()会报错,原因是指向文件xxx的指针已经直到了文件结尾,
需要重新指定一下:xxx.seek(0,0)重定向于文件开始处,其他的:xxx.seek(0,2)重定向于文件结尾处

xxx.tell()读取从文件开头到文件指向指针位置的字节数,显然如果xxx.seek(0,0)了为0,xxx.seek(0,2)之后为文件内容实际大小。

002:写文件

>>> xxx.close()
>>> xxx = file('d:\\python\\test.txt','w')
>>> xxx.write('lazy')
>>> xxx.write(' test')
>>> xxx.write(' test.txt\n')
>>> xxx.writelines(['billrice','ricerice'])
>>> xxx.close()
>>> xxx = file("d:\\python\\test.txt",'r')
>>> a = xxx.read()
>>> print a

lazy test test.txt
billricericerice

注意不要在循环中调用write写,总是失败:

        for x in range(len(List)):
            outPut.write (List[x])

可以这样:

       outStr=''

       for x in range(len(List)):
            #print (List[x]+'\n')
            outStr += List[x]+'\n'

      fileWrite.writelines(outStr)

初步学习Python,这个总结很棒:

http://www.cnblogs.com/taowen/articles/11239.aspx

003:判断文件是否存在:

os.path.exists(self.savePath+"\\"+self.fileName)



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值