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动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- 使用OS Watcher监控操作系统
- Python将excel导入到mysql中
- 什么是Mac OS X?跟Linux有什么区别
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例