Python でファイル名を取得して保存する方法は何ですか?
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
- オープン
- 書き込む
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)
このメソッドは、ファイル名を取り出して別のファイルに保存するのに使われます。