1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Automating GIS Processes 2024 写経 Lesson 2 (Managing file paths)

Posted at

さて、Geopandas を使って Python で空間データを扱いま、、、、せん。

その前に、pathlibのはなしです。

When working with data, it is important to keep track of where which input files are stored, and where which output files should be written. This is especially important when moving between computers or between virtual machines, like, for instance, the CSC Notebooks platform. Using a distributed code repository or versioning system, such as GitHub, adds another layer of complexity: file paths should often be relative to the git repo, or to the current file, as the repository can be cloned to any location on a different computer (and already a different user name on your school and personal computers might break things).

入出力ファイルがどこにあるのか、どこに置くのか、とても重要な話です。

Earlier, file paths have often been hard-coded strings, text values. If, for instance, an output file name had to be derived from an input file name, all kind of slicing and other string manipulation methods would be used.

かつてのやり方は、ファイルのパスをハードコーディングしてスライスなどの文字列操作をする、でした。

More recently, the os.path module of Python became popular, that allowed to split a path into directories, and file names into base names and file extensions. However, manipulating file paths still required knowledge about the computer a script would ultimately run on. For instance, on all Unix-based operating systems, such as Linux or MacOS, directories are separated by forward-slashes (/), while Microsoft Windows uses back-slashes () (this particular problem can be worked around with os.sep and os.path.join, but not in a very convenient way).

最近では、Pythonのos.pathで、パスをディレクトリに分割し、ファイル名をベース名とファイル拡張子に分割できます。ただ、OSの違い(UnixベースとWindowsの違い)、/\(バックスラッシュ)の違いの吸収については、os.path.joinで対処できるものの、利便性がそれほど良くありません。

Since Python 3.4 (so, fairly recently), there exists a built-in module that eases much of the hassle with managing file paths: pathlib <https://docs.python.org/3/library/pathlib.html>__. It provides an abstract layer on top of the actual operating system file paths that is consistent across computers. A pathlib.Path() object can be initiated with a file path (as a str), when created without an argument, it refers to the directory of the script or notebook file.

pathlib.Path()オブジェクトはファイルパス (str として)で開始できます。引数なしで作成すると、カレントディレクトリを指します

import pathlib
pathlib.Path()

image.png

resolve()で絶対パスを見ます。当然、!pwdと同じ結果です。

path = pathlib.Path()
path = path.resolve()
path

image.png

pathlib.Path()オブジェクトのプロパティをいくつか操作してみましょう。

print(f"存在する?:{path.exists()}")
print(f"ディレクトリ?:{path.is_dir()}")
print(f"ファイル?:{path.is_file()}")

image.png

プロパティ操作でpathを削除することもできます。間違って、"/content"を消さないように、適当なディレクトリを作ってからです。

target_directory  = pathlib.Path("消したいディレクトリ")
print(f"存在する?:{target_directory.exists()}")
target_directory.rmdir()

実行前
image.png

image.png

実行後
image.png

To refer to a directory inside path, use the / (division operator) to append another path component (can be a string). For instance, to refer to a folder data within the same directory as this notebook, write the following:

パス内のディレクトリを参照するには、/pathlib.Path()オブジェクトに付けるだけです。

data_directory = path / "data"
data_directory

image.png

Path() objects can be used (almost) anywhere a file path is expected as a variable of type str, as it automatically typecasts (converts) itself to a suitable type.

pathlib.Path()オブジェクトは、ファイルパスが str の変数として期待されるところではキャスト(型変換)無しで基本はOKです。Pythonの良いところでもあり、悪いところでもあると思います。

講釈が終わったところで、ファイルの読み込みについてです。

カレントディレクトリにdataというディレクトリを作り、そこにファイルを置きます。
ディレクトリの絶対パスは固定値なので、固定値として定義します。

# location (directory) of the notebook
import pathlib
NOTEBOOK_PATH = pathlib.Path().resolve()
DATA_DIRECTORY = NOTEBOOK_PATH / "data"

print(NOTEBOOK_PATH)
print(DATA_DIRECTORY)

image.png

Python では定数というものはありません。慣習的に大文字+アンダースコアの変数を固定値とみなして使います。

続きます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?