Python提取文件名并保存的方法可以通过使用os模块中的相关函数来实现。具体步骤如下:
os.path.basename()
函数来获取文件名,该函数接收文件路径作为参数,并返回文件名。import os
file_path = "/path/to/file.txt"
file_name = os.path.basename(file_path)
print(file_name) # 输出: file.txt
os.path.splitext()
函数,该函数也接收文件路径作为参数,并返回一个包含文件名和文件扩展名的元组。import os
file_path = "/path/to/file.txt"
file_name, file_ext = os.path.splitext(file_path)
print(file_name) # 输出: /path/to/file
print(file_ext) # 输出: .txt
open()
函数打开一个新文件,然后使用write()
方法将文件名写入该文件。import os
file_path = "/path/to/file.txt"
file_name = os.path.basename(file_path)
new_file_path = "/path/to/new_file.txt"
with open(new_file_path, "w") as new_file:
new_file.write(file_name)
以上方法可以用于提取文件名并保存到另一个文件中。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: python怎么创建一个集合