python学习之二

文件的操作:

    打开文件的方式: 

>>> open('test.txt', 'w')
<open file 'test.txt', mode 'w' at 0x2b00cac7e6f0>
>>> file('test.txt', 'w')
<open file 'test.txt', mode 'w' at 0x2b00cac7e780>
>>> f = open ('test.txt', 'w')
>>> print f
<open file 'test.txt', mode 'w' at 0x2b00cac7e6f0>
      注: w -> 写操作  r->读操作  a-> 文本末尾添加  r+ ->可读可写 b->二进制读写  需要和w r 配合使用 比如:rb wb

   读文件操作 :

 1. 默认读完

>>> f = open('test1.txt', 'r')
>>> f.read()
 2. 逐行读取文件

>>> f = open('test1.txt', 'r')
>>> f.readline()

>>> f=open('test1.txt', 'r')
>>> f.readline()
'This is the first line in the file.\n'
>>> f.readline()
'this is the second line in the file.\n'
>>> f.readline()
'this is the third line in the file.\n'
>>> f.readline()
'this is the 4th line in the file.\n'
>>> f.readline()
'this is the 5th line in the file.\n'
>>> f.readline()
'this is the 6th line in the file.\n'
>>> f.readline()
'this is the 7th line in the file.\n'
>>> f.readline()
'this is the 8th line in the file.\n'
>>> f.readline()
'this is the 9th line in the file.\n'
>>> f.readline()
'this is the 10th line in the file.\n'
>>> f.readline()
'\n'
>>> f.readline()
''

 3. 读全文,系统自动以‘\n’结尾表示换行,并且每行作为list成员,以逗号分隔!

>>> f = open('test1.txt', 'r')
>>> f.readlines()
>>> f=open('test1.txt', 'r')
>>> f.readlines()
['This is the first line in the file.\n', 'this is the second line in the file.\n', 'this is the third line in the file.\n', 'this is the 4th line in the file.\n', 'this is the 5th line in the file.\n', 'this is the 6th line in the file.\n', 'this is the 7th line in the file.\n', 'this is the 8th line in the file.\n', 'this is the 9th line in the file.\n', 'this is the 10th line in the file.\n', '\n']

for 循环读取文件:

>>> f=open('test1.txt', 'r')
>>> for line in f:
...    print line
... 
This is the first line in the file.

this is the second line in the file.

this is the third line in the file.

this is the 4th line in the file.

this is the 5th line in the file.

this is the 6th line in the file.

this is the 7th line in the file.

this is the 8th line in the file.

this is the 9th line in the file.

this is the 10th line in the file.

以读写方式打开文件,查找偏移量对应的值并读出。

>>> f=open('test2.txt', 'r+')
>>> f.write('0123456789\n')
>>> f.seek(5)
>>> f.read(1)
'5'
>>> f.seek(-3, 2)
>>> f.read(1)
'8'







    

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值