[英]Using os.path.splitext to seperate filename and extension
I am creating a program in which I need to separate the file name and the file extension of a fle. 我正在创建一个程序,需要在其中分隔文件的文件名和文件扩展名。 The way i am doing this is by using
我这样做的方式是通过使用
os.path.splitext('')
I was simply wondering if anybody knows how I could save the two parts of the file as two variables. 我只是想知道是否有人知道如何将文件的两部分保存为两个变量。
os.path.splitext()
returns a tuple: os.path.splitext()
返回一个元组:
>>> import os
>>> name_parts = os.path.splitext('data.txt')
>>> name_parts
('data', '.txt')
You can take it apart: 您可以拆开它:
>>> body, ext = name_parts
Now: 现在:
>>> body
'data'
and: 和:
>>> ext
'.txt'
You can do this in one step: 您可以一步完成此操作:
>>> body, ext = os.path.splitext('data.txt')
This is called tuple unpacking. 这称为元组拆包。
For example: 例如:
>>> a = 1
>>> b = 2
You can swap their values with: 您可以将它们的值交换为:
>>> a, b = b, a
You can also place parenthesis around. 您也可以在圆括号中放置括号。 It is not necessary but may help to understand what is going on:
这不是必需的,但可能有助于了解发生了什么:
>>> (a, b) = (b, a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.