[python 学习] IO操作之读写文件

一、读取全部文件:

# -*- coding: utf-8 -*-

f = open('qq_url.txt','r');
print f.read();
f.close();

二、读取规定长度文件

# -*- coding: utf-8 -*-

f = open('qq_url.txt','r');
print f.read(10);
f.close();

三、按行读取文件

# -*- coding: utf-8 -*-

url_list = []
f = open('qq_url.txt','r')
line = f.readline()
while line:
    url_list.append(line)
    line = f.readline()
f.close()
print url_list

四、读取二进制文件(图片等)

# -*- coding: utf-8 -*-

f = open('demo.jpg','rb')
print f.read()
f.close()

五、文件内容编码

# -*- coding: utf-8 -*-

f = open('utf8.txt','r')
content = f.read()
# print content
print content.decode('utf-8')
f.close()

 

六、写文件

# -*- coding: utf-8 -*-

f = open('write.txt','w')
f.write("test for writingf")
f.close()

 

 

posted @ 2017-08-28 13:48  S3c0ldW4ng  阅读(280)  评论(0编辑  收藏  举报