在Python中通过Applescript打开pwdir文件夹中的文件

2024-09-20 04:10:49 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中打开当前工作目录的temp文件夹中可用的文件

我试过了

pwdir=os.getcwd()
tempdir=pwdir+"/temp/test.txt"
f=open(tempdir,'r+')

当我打印tempdir的路径时,它正确地显示出来了,文件的内容也被读取了。在

当我试图从一个Applescript中组合这个操作时,这个Applescript调用了这个python脚本。我遇到了这样一个错误

^{pr2}$

编辑:

我使用Applescript中的Shell脚本来调用这个pythonscript

do shell script "/Users/mymac/Documents/'Microsoft User Data'/test.py"

编辑:

Python代码:

tempdir = os.path.join(os.getcwd(),'temp','htmlinput.html')
print tempdir
with open(tempdir) as f:
    html=f.read()

来自终端的Python输出:(工作非常好)

/Users/mymac/Documents/Microsoft User Data/Outlook Script Menu Items/temp/htmlinput.html

我还可以看到文件内容。在

Applescript代码:

do shell script "/Users/mymac/Documents/'Microsoft User Data'/'Outlook Script Menu Items'/new.py"

Applescript错误:

error "Microsoft Outlook got an error: Traceback (most recent call last):
  File \"/Users/mymac/Documents/Microsoft User Data/Outlook Script Menu Items/new.py\", line 12, in <module>
    with open(tempdir) as f:
IOError: [Errno 2] No such file or directory: '/temp/htmlinput.html'" number 1

Tags: 文件pydataoshtmlopenuserstemp
2条回答

我一般不知道Applescript或osx。看起来脚本是从根文件夹运行的,并且操作系统getcwd()返回“/”。脚本本身的目录是sys.path[0],如果是单个脚本而不是包,则为当前模块的目录dirname(__file__)。尝试下列方法之一

import os, sys
tempdir = os.path.join(sys.path[0], 'temp', 'temp.txt') 

或者

^{pr2}$

双斜杠是你的问题。在Python中连接文件名和路径名的正确方法是使用os.path.join。尝试:

tempdir = os.path.join(os.getcwd(), 'temp', 'test.txt')

此外,您可能应该:

^{pr2}$

这将确保即使出现错误,tempdir也会关闭。在

编辑:

我们需要了解当AppleScript调用脚本时,tempdir是什么,而不是从终端调用脚本时。如果你这么做的话

tempdir = os.path.join(os.getcwd(),'temp','htmlinput.html')
with open('/Users/mymac/Documents/temp.txt', 'w') as fwrite:
    fwrite.write(tempdir)

文件/Users/mymac/Documents/temp.txt中到底有什么结果?在

相关问题 更多 >