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( )