Python提取文件名并保存的方法可以通过使用os模块中的相关函数来实现。具体步骤如下:
- 使用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模块的
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)
以上方法可以用于提取文件名并保存到另一个文件中。