#!/usr/bin/python # -*- coding: utf-8 -*- #Author: zhaosj ###Python 打开文件### #爬虫的初期工作常常要把数据存储到文件中 #Python 中通过open()函数打开文件 open(name[,mode[,buffering]])
#open()函数使用的文件名作为唯一强制参数,然后返回一个文件对象. #模式(mode)和缓冲(buffering)是可选参数.在Python的文件操作中,mode参数的输入是有必要的,而buffering使用较少 f = open('/home/workspace/script_Monitor_2.7.5/logs/dra_monitor_start.log')
#'r' :读模式 #'w' :写模式 #'a' :追加模式 #'b' :二进制模式(可添加到其它模式中使用) #'+' :读/写模式(可添加到其它模式中使用)
#读写文件 f = open('/home/workspace/script_Monitor_2.7.5/logs/dra_monitor_start222.log','w+') f.write('hello zhaoshujing')
#执行结果:
当文件不存在的时候,会创建一个文件
如果在次运行程序,txt文件的内容不会继续添加,可以修改模式参数为'r+',便可以一直写入文件.
#Python读取文件通过read()方法
f = open('/home/workspace/script_Monitor_2.7.5/logs/dra_monitor_start222.log','r')
content = f.read()
print(content)
#关闭文件
f.close()
#执行结果: