您的位置:首页 > 编程语言 > Python开发

Python 文件操作

2013-01-03 23:06 417 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python