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

Python 文件读写操作记录

2016-05-02 10:40 423 查看
# 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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python 文件读写 os