用类方法和静态方法实现:一个是追加写文件一行内容,一个是读指定行号的内容
#coding=utf-8
class handle_file(object):
def __init__(self,file_path):
self.file_path=file_path
@classmethod
def write_file(cls,file_path,content):
with open(file_path,'a') as fp:
fp.write(content)
def readContent(self):
with open(self.file_path) as fp:
return fp.read()
@staticmethod
def read_file(file_path,line_nbr):
with open(file_path,'r') as fp:
strList=fp.readlines()
print strList
if strList[line_nbr-1]==' ':
print 'error'
else:
return strList[line_nbr-1]
s="1ssdfsdf 2dfsdfs 3sdfsdf "
operation=handle_file('d:\0410.txt')
handle_file.write_file('d:\0410.txt',s)
print handle_file.read_file('d:\0410.txt',2)
print operation.readContent()
c:Python27Scripts>python task_test.py
['1ssdfsdf ', '2dfsdfs ', '3sdfsdf ']
2dfsdfs
1ssdfsdf
2dfsdfs
3sdfsdf