Programming」カテゴリーアーカイブ

プログラミング全般に関するカテゴリーです。

Pythonでファイルをコピーする方法

Pythonでファイルをコピーしたい場合はshutilモジュールのcopyが使えます。

>>> import shutil
>>> shutil.copy('/path/to/src', '/path/to/dst')

ファイルの作成時刻や変更時刻などはコピーされませんので、必要に応じてcopystatも追加してください。

>>> shutil.copy('/path/to/src', '/path/to/dst')
>>> shutil.copystat('/path/to/src', '/path/to/dst')
>>> import os, time
>>> time.strftime('%Y-%m-%d %I:%M:%S', time.localtime(os.path.getmtime('/path/to/src')))
'2018-11-21 09:58:03'
>>> time.strftime('%Y-%m-%d %I:%M:%S', time.localtime(os.path.getmtime('/path/to/dst')))
'2018-11-21 09:58:03'

Pythonでファイル作成時刻や最終更新時刻を取得する方法についてはこちらも参考にしてください。


copyはディレクトリに対しても実行可能なようです。

Pythonでファイルの作成時刻や最終更新時刻を取得する方法

Pythonでファイルの作成時刻や最終更新時刻を取得するにはgetctimegetmtimeを使うと良いそうです。

使い方は次のような感じです。

作成時刻

>>> import os
>>> os.path.getctime('/path/to/file')
1542761883.7563891

最終更新時刻

>>> os.path.getmtime('/path/to/file')
1542761883.7563891

最終アクセス時刻

>>> os.path.getatime('/path/to/file')
1542761883.7563891

戻り値はepochからの経過秒数になっています。timeモジュールを使うと読み易い形に変換できます。

>>> import time
>>> time.strftime('%Y-%m-%d %I:%M:%S', time.localtime(1542761883.7563891))
'2018-11-21 09:58:03'

Unityでゲームを終了させるコード

Unityのゲームを終了させたい場合、右上の×ボタンとかAlt+F4で終了させることもできますが、もう少しスマートにしたい場合はApplication.Quitを使うとよいそうです。

使い方

void Update()
{
  if (Input.GetKey(KeyCode.Escape)) {
    Application.Quit();
  }
}

ちなみに上のコードは、UnityのEditor上でDebugしているときには使えません。Editor上でDebugを終了させたい場合はUnityEditor.EditorApplication.isPlayingを使って次のような感じにすることができるそうです。

void Update()
{
  if (Input.GetKey(KeyCode.Escape)) {
#if UNITY_EDITOR
    UnityEditor.EditorApplication.isPlaying = false;
#else
    Application.Quit();
#endif
  }
}

リンク

Unity – Scripting API: Application.Quit
https://docs.unity3d.com/ScriptReference/Application.Quit.html

Application.Quit not working?! – Unity Answers
https://answers.unity.com/questions/899037/applicationquit-not-working-1.html