【问题标题】:Opening a file in pwdir's folder in Python through Applescript通过 Applescript 在 Python 中打开 pwdir 文件夹中的文件
【发布时间】:2011-10-10 15:12:24
【问题描述】:

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

我试过了

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

当我打印 tempdir 的路径时,它显示正确,并且文件的内容也被读取。

当我尝试从调用此 python 脚本的 Applescript 中组合此操作时。我收到这样的错误

f=open(pwdir1,'r+')
IOError: [Errno 2] No such file or directory: '//temp/test.txt'" number 1

编辑:

我正在使用 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

【问题讨论】:

  • @eryksun 同样的问题..更新了问题
  • 试试@eryksun 的建议或我在编辑中建议的。 Eryksun,你需要更频繁地发布答案而不是 cmets,这样我才能给你投票。
  • @eryksun os.path.join(os.path.dirname(file), 'temp', 'temp.txt') 有效..谢谢
  • @all 如果这是一个罕见的问题,这值得一票:)

标签: python macos scripting file-io applescript


【解决方案1】:

我不知道 Applescript 或一般的 OS X。看起来脚本正在从根文件夹运行,并且 os.getcwd() 返回“/”。脚本本身的目录是 sys.path[0] 或当前模块的目录名 -- dirname(__file__) -- 如果它是单个脚本而不是包。尝试以下方法之一

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

import os
tempdir = os.path.join(os.path.dirname(__file__), 'temp', 'temp.txt')

【讨论】:

    【解决方案2】:

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

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

    另外,你可能应该这样做:

    with open(tempdir) as f:
    

    即使出现错误,也可以确保 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 文件中到底有什么结果?

    【讨论】:

    • @agf..不是同样的错误。它单独在 Python 中打开良好,当我尝试使用不同的文件时,shell 脚本中也没有问题..
    • 从错误消息中看起来你不只是传递它os.path.join(os.getcwd(), 'temp', 'test.txt') 或者它不会有额外的双引号和“数字 1”。请尝试编辑您的帖子以添加print os.path.join(os.getcwd(), 'temp', 'test.txt') 显示的内容以及您在open(os.path.join(os.getcwd(), 'temp', 'test.txt')) 时收到的错误确切
    猜你喜欢
    • 2012-06-30
    • 2010-09-23
    • 2020-03-08
    • 2015-03-13
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 2018-01-27
    • 2018-02-15
    相关资源
    最近更新 更多