D2B 发表于 2018-11-14 16:26:14

关于with的用法

各位亲们,请问下小甲鱼课后作业第46讲关于描述符的动动手第二题,代码清单如下:
import time

    class Record:
      def __init__(self, initval=None, name=None):
            self.val = initval
            self.name = name
            self.filename = "record.txt"

      def __get__(self, instance, owner):
            with open(self.filename, 'a', encoding='utf-8') as f:
                f.write("%s 变量于北京时间 %s 被读取,%s = %s\n" % \
                        (self.name, time.ctime(), self.name, str(self.val)))
            return self.val

      def __set__(self, instance, value):
            filename = "%s_record.txt" % self.name
            with open(self.filename, 'a', encoding='utf-8') as f:
                f.write("%s 变量于北京时间 %s 被修改, %s = %s\n" % \
                        (self.name, time.ctime(), self.name, str(value)))
            self.val = value

请问下with open(self.filename,'a','encoding-'utf-8'')中的这个'a'是语法结构吗还是别名,为什么这里会有一个'a'呢?作用是什么?
谢谢指教~

塔利班 发表于 2018-11-14 16:42:14

'a'是文件读写模式,表示追加写入
文件系统那里应该有讲过啊
还有'r','rb','w'等等等

D2B 发表于 2018-11-14 17:11:05

塔利班 发表于 2018-11-14 16:42
'a'是文件读写模式,表示追加写入
文件系统那里应该有讲过啊
还有'r','rb','w'等等等

多谢多谢,脑子笨,时间一长就有点忘记了。。{:5_106:}
页: [1]
查看完整版本: 关于with的用法