![](/img/trans.png)
[英]MAC OS & Python script not able to read file when executed from Applescript or with Py2app
[英]python rename script not working when executed from finder (Mac)
大家好
我是python的新手,但是我寫了一個小腳本來幫助我重命名文件擴展名。 它很短,所以我將其發布在這里:
import os
for filename in os.listdir("."):
if filename.endswith("gd"):
os.rename(filename, filename + ".dat")
現在,由於我有幾個目錄需要在其中執行,所以總是導航到終端中的文件夾並使用命令從那里執行它變得很煩人
python renamescrip.py
現在,我偶然發現了一些建議,這些建議將使Finder中雙擊python腳本即可執行,這對我來說使工作變得更加輕松,因為我只需要復制並粘貼namedname.py到我想要的文件夾中重命名文件,然后雙擊執行它。
我遵循了以下指示信息: http : //skillfulness.blogspot.de/2010/12/how-to-run-python-script-from-mac-os-x.html ,其中顯示了如何創建.command文件。
但是,當我雙擊renamescript.command文件時,它沒有更改目錄中的文件名。
我還嘗試使用Python啟動器打開.py文件,但這也沒有更改文件名。
但是,兩次都打開了終端窗口,並顯示以下消息:
cd '/path to directory with files to rename/' && '/usr/local/bin/pythonw' '/path to directory with files to rename/renamescript.py' && echo Exit status: $? && exit 1
Exit status: 0
logout
或者,如果我單擊.command文件,它只是:
/path to directory with files to rename/renamescript.command ; exit;
logout
我究竟做錯了什么?
雙擊時,您使用的當前目錄與從Shell運行時所在的目錄不同。 這會使os.listdir(".")
找不到您認為應該的文件。 您應該在腳本開頭使用以下命令更改目錄
os.chdir(os.path.dirname(os.path.abspath(__file__)))
在您的os.listdir
調用之前
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.