- file.read(n) //n为字节数,读到文件末尾,继续读则为空字符
- //n无或负数,均为全部读取
- In [21]: f = open('/root/README.txt','r')
- In [22]: f.read(5)
- Out[22]: 'Curre'
- In [23]: f.read(5)
- Out[23]: 'nt ve'
- In [24]: f.read(5)
- Out[24]: 'rsion'
- -------------
- f.read()
- Out[25]: " information\n---------------------------\n\nPlease open manual.pdf for a PDF version of IPython's user manual"
- In [26]: f.read()
- Out[26]: ''
- f = open('/root/outfile.txt','w')
- f.writelines('%s\n'%i for i in range(10)) //writelines()必须手动分行
- f.close()
- root@debian:~# cat outfile.txt
- 0
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
urllib
文件对象只支持read(),readline(),readlines(),close()等只读方法
- import urllib
- url_file = urllib.urlopen("http://www.baidu.com/gaoji/preferences.html")
- docs = url_file.read()
- docs[0:]
- '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r\n<html xmlns="http://www.w3.org/1999/xhtml">\r\n<head>\r\n<meta http-equiv="Content-Type" content="text/html