用类方法和静态方法实现:一个是追加写文件一行内容,一个是读指定行号的内容

 

#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]==\’\n\’:

                print \’error\’

            else:

                return strList[line_nbr-1]

 

 

 

s=”1ssdfsdf\n2dfsdfs\n3sdfsdf\n”

 

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:\Python27\Scripts>python task_test.py

[\’1ssdfsdf\n\’, \’2dfsdfs\n\’, \’3sdfsdf\n\’]

2dfsdfs

 

1ssdfsdf

2dfsdfs

3sdfsdf

版权声明:本文为xiaxiaoxu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/xiaxiaoxu/p/8778210.html