1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Windows上のPythonでファイルパスを指定する

Posted at

サマリ

今までLinux上でしかPythonを動かしたことがなかったので、Windows上のPythonを動かした時にファイルパスの指定ができなくて、小一時間悩みました。

今回困ったこと

例えば、こんな具合でWindowsのファイルパスを指定します。

>>> file_path = "C:\Users\hogehoge\fugafuga"

そうなるとこんなエラーが出ます。

   File "<stdin>", line 1
     file_path = "C:\Users\hogehoge\fugafuga"
                                                        ^
 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

なんで?

LinuxやMacでファイルパスを指定する際は/(スラッシュ)でディレクトリを区切りますが、Windowsはファイルパスを\(バックスラッシュ)区切ってます。
で、このバックスラッシュが悪さをしています。
Python内でのバックスラッシュはエスケープシーケンスの役割を持っています。改行などの通常の文字列では表せない機能を持つ文字になりますので、ファイルパスを指定するのに余計なことをしているんですね。

raw文字でエスケープシーケンスを無効化

というわけで、バックスラッシュをエスケープシーケンスを無視させて単純な文字列として認識させる必要があります。
書き方は簡単で、ファイルパスの前にr:と付け加えるだけ。raw = 生の頭文字でr:ということになります。

 >>> file_path = r"C:\Users\hogehoge\fugafuga"
 >>> print (file_path)
 C:\Users\hogehoge\fugafuga

他にもosモジュールでos.path.join()関数を使用する手法があります。
こちらについてはまた後ほどに。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?