LoginSignup
0
0

More than 1 year has passed since last update.

tkinter.filedialogで取得したパスのセパレータを信用してはいけない

Last updated at Posted at 2022-04-04

Windowsでのお話です。
tkinter.filedialog.asksaveasfilename()で指定したファイルがあるフォルダを開きたいとします。
直感的に以下のコードを書きます。

from subprocess import Popen
from tkinter.filedialog import asksaveasfilename

file_path = asksaveasfilename()    # D:\github\sample.json を選択する
if file_path:
    Popen(['explorer', '/select,'+file_path])
#=> PCが開く

なんで???

print(file_path)
D:/github/sample.json

セパレータがバックスラッシュではなくスラッシュになっている。

from os.path import sep
from subprocess import Popen
from tkinter.filedialog import asksaveasfilename

file_path = asksaveasfilename()    # D:\github\sample.json を選択する
if file_path:
    file_path = file_path.replace('/', sep)    # '/'をプラットフォームのセパレータに置換
    Popen(['explorer', '/select,'+file_path])
#=> D:\githubが開く

ヨシ!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0