获取输入文件的名称和拓展名
时间: 2024-03-15 12:47:42 浏览: 21
好的,你可以使用Python中的os模块来获取文件名和拓展名。具体代码如下:
```python
import os
filename = "example.txt"
basename = os.path.basename(filename) # 获取文件名
extension = os.path.splitext(basename)[1] # 获取拓展名
print("文件名:", basename)
print("拓展名:", extension)
```
以上代码中,我们使用了`os.path.basename`函数来获取文件名,并使用`os.path.splitext`函数来获取拓展名。注意,`os.path.splitext`函数返回值是一个元组,其中第二项就是拓展名,因此我们使用索引`[1]`来获取。
相关问题
C# 获取输入文件的名称和拓展名
好的,你可以使用C#中的Path类来获取文件名和拓展名。具体代码如下:
```csharp
using System.IO;
string filename = "example.txt";
string basename = Path.GetFileName(filename); // 获取文件名
string extension = Path.GetExtension(filename); // 获取拓展名
Console.WriteLine("文件名:" + basename);
Console.WriteLine("拓展名:" + extension);
```
以上代码中,我们使用了`Path.GetFileName`方法来获取文件名,并使用`Path.GetExtension`方法来获取拓展名。注意,`Path.GetExtension`方法返回的拓展名包含点号("."),因此如果需要去掉点号,可以使用`Substring`方法或`TrimStart`方法来去掉。
链接文件的名称和拓展名
好的,你可以将获取文件名和拓展名的代码组合起来,来获得完整的文件名,即文件名加上拓展名。具体代码如下:
```csharp
using System.IO;
string filename = "example.txt";
string basename = Path.GetFileName(filename); // 获取文件名
string extension = Path.GetExtension(filename); // 获取拓展名
string fullFilename = basename + extension; // 连接文件名和拓展名
Console.WriteLine("完整文件名:" + fullFilename);
```
以上代码中,我们在获取文件名和拓展名的基础上,使用"+"符号将它们连接起来,从而获得完整的文件名。注意,如果想要去掉拓展名中的点号,可以使用`Substring`方法或`TrimStart`方法来去掉。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)