Python 3.6 中针对文件系统的神奇方法
Python3.6首次发布于2016年,尽管它已经发布了很长一段时间,但它引入的许多特性都没有得到充分利用,而且相当酷。下面是其中的三个。
分隔数字常数
快回答哪个更大,10000000还是200000?你在看代码时能正确回答吗?根据当地的习惯,在写作中,你会用10,000,000或10.000.000来表示第一个数字。问题是,Python使用逗号和句号是用于其他地方。
幸运的是,从Python3.6开始,你可以使用下划线来分隔数字。这在代码中和使用字符串的int()转换器时都可以使用:
importmath
math.log(10_000_000)/math.log(10)
7.0
math.log(int("10_000_000"))/math.log(10)
7.0
Tau是对的
45度角用弧度表示是多少?一个正确的答案是π/4,但这有点难记。记住45度角是一个八分之一的转角要容易得多。正如TauManifesto所解释的,2π,称为Τ,是一个更自然的常数。
在Python3.6及以后的版本中,你的数学代码可以使用更直观的常数:
print("Tanofaneighthturnshouldbe1,got",round(math.tan(math.tau/8),2))
print("Cosofansixthturnshouldbe1/2,got",round(math.cos(math.tau/6),2))
print("Sinofaquarterturnshouldbe1,go",round(math.sin(math.tau/4),2))
Tanofaneighthturnshouldbe1,got1.0
Cosofansixthturnshouldbe1/2,got0.5
Sinofaquarterturnshouldbe1,go1.0
os.fspath
从Python3.6开始,有一个神奇的方法表示“转换为文件系统路径”。当给定一个str或bytes时,它返回输入。
对于所有类型的对象,它寻找__fspath__方法并调用它。这允许传递的对象是“带有元数据的文件名”。
像open()或stat这样的普通函数仍然能够使用它们,只要__fspath__返回正确的东西。
例如,这里有一个函数将一些数据写入一个文件,然后检查其大小。它还将文件名记录到标准输出,以便追踪:
defwrite_and_test(filename):
print("writinginto",filename)
withopen(filename,"w")asfpout:
fpout.write("hello")
print("sizeof",filename,"is",os.path.getsize(filename))
你可以用你期望的方式来调用它,用一个字符串作为文件名:
write_and_test("plain.txt")
writingintoplain.txt
sizeofplain.txtis5
然而,可以定义一个新的类,为文件名的字符串表示法添加信息。这样可以使日志记录更加详细,而不改变原来的功能:
classDocumentedFileName:
def__init__(self,fname,why):
self.fname=fname
self.why=why
def__fspath__(self):
returnself.fname
def__repr__(self):
returnf"DocumentedFileName(fname={self.fname!r},why={self.why!r})"
用DocumentedFileName实例作为输入运行该函数,允许open和os.getsize函数继续工作,同时增强日志:
write_and_test(DocumentedFileName("documented.txt","becauseit'sfun"))
writingintoDocumentedFileName(fname='documented.txt',why="becauseit'sfun")
sizeofDocumentedFileName(fname='documented.txt',why="becauseit'sfun")is5
以上内容为大家介绍了Python3.6中针对文件系统的神奇方法,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。http://www.mobiletrain.org/

相关推荐HOT
更多>>
python中ndarray与list转换的方法
python中ndarray与list转换的方法在python数据类型中,list元素可以任意类型组合,而ndarray元素类型必须相同,但是ndarray可以更方便的对多维...详情>>
2023-11-10 08:51:14
python中OrdereDict如何使用?
python中OrdereDict如何使用?我们在对数据进行处理时,如果能够使它们保存顺序的排序,那么用起来会非常的便利。不过字典本身就是没有顺序的,...详情>>
2023-11-10 07:05:00
python中如何使用scipy.fftpack模块计算快速傅里叶变换?
python中如何使用scipy.fftpack模块计算快速傅里叶变换?在编程中,快速傅里叶变换是工程中非常有价值的一类算法,它可以将时域和频域的信号相互...详情>>
2023-11-10 05:50:23
zip()函数如何在python中遍历多个列表?
zip()函数如何在python中遍历多个列表?下面我们就python中zip的说明、语法、使用注意点进行讲解,然后带来遍历多个列表的实例。1、说明zip()函...详情>>
2023-11-10 05:38:33热门推荐
python concat函数有何用法?
沸python里函数装饰器怎么使用?
热如何实现python中的continue语句?
热python中的冒泡排序是什么?
新python中str函数是什么
如何使用python实现项目进度显示?
python中ndarray与list转换的方法
python复制文件的方法整理
Python中numpy数组如何添加元素
python有几种可视化图形库?
python中xlwings是什么?
python上下文管理器的基本介绍
Python自动化测试基础必备知识点一
python中OrdereDict如何使用?
技术干货






