# coding=utf-8

import os

# 此文件只为记录方法,不可直接执行
# read ++++++++++++++++++++++++++++++++++++++++++++++++++

file_name = "test.txt"
file_path = os.getcwd() + os.sep + "data" + os.sep + file_name
file_obj = open(file_path, "r")

# 读取所有内容------------------------------------
try:
file_content = file_obj.read()
print file_content
finally:
file_obj.close()

# 读取固定字节------------------------------------
file_obj_byte = open(file_path, "rb")
try:
while 1:
chunk = file_obj.read(10)
if not chunk:
break
print chunk
finally:
file_obj.close()

# 按行读取---------------------------------------
try:
for ele in file_obj.readlines():
print ele
finally:
file_obj.close()

# write ++++++++++++++++++++++++++++++++++++++++++++++++++
content = "test data"
#
# 写文本文件
file_obj = open("out.txt", "w")
# 写二进制文件
file_obj = open("out.txt", "wb")
# 追加文件
file_obj = open("out.txt", "w+")

# 一次性写入
file_obj.write(content)
# 按行写入,较上者效率高,连续写入文件,没有换行。
file_obj.writelines(content)
file_obj.close()