python入门 读写文件

巴扎黑
巴扎黑 原创
2016-12-07 11:19:58 796浏览

1.打开文件,读取所有内容

file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )

2.读取固定字节

file_object = open('abinfile', 'rb')
try:
while True:
chunk = file_object.read(100)
if not chunk:
break
do_something_with(chunk)
finally:
file_object.close( )

3.读取文件一行

f = open("D:\\test\\BlueSoftSetup.log","r")

try:

while True:

line = f.readline()

if line:

print(line)

else:

break;

finally:

f.close();

4.写文件

写文本文件
output = open('data', 'w')

写二进制文件
output = open('data', 'wb')

追加写文件
output = open('data', 'w+')

写数据
file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
上一条:python shelve模块 下一条:python 元类