Excel Applescript:在不使用旧文件名的情况下写入新文件

Excel Applescript:在不使用旧文件名的情况下写入新文件,excel,macos,applescript,applescript-objc,Excel,Macos,Applescript,Applescript Objc,前言:我的Applescript获取一个Excel文件,并将其数据复制到一个新的纯文本文件中 在与现有Excel文件相同的位置写入新文本文件时遇到问题,但没有原始文件的文件名 例如:我的Excel文件是“FilenameA.xls”,当我保存新文本文件时,它会将其保存为“FilenameA.xlsFilenameB.txt” 如何将此新文件保存到同一位置,但使用自己的文件名 注意:当我使用(桌面路径为文本)时,它可以工作,但我不会总是将这些保存到我的桌面 set myFile to open f

前言:我的Applescript获取一个Excel文件,并将其数据复制到一个新的纯文本文件中

在与现有Excel文件相同的位置写入新文本文件时遇到问题,但没有原始文件的文件名

例如:我的Excel文件是“FilenameA.xls”,当我保存新文本文件时,它会将其保存为“FilenameA.xlsFilenameB.txt”

如何将此新文件保存到同一位置,但使用自己的文件名

注意:当我使用
(桌面路径为文本)
时,它可以工作,但我不会总是将这些保存到我的桌面

set myFile to open for access (path to desktop as text) & blahBlah & ".txt" with write permission
当我尝试下面的脚本时,它会给出原始文件名和新文件名

set myFile to open for access (fileName) & blahBlah & ".txt" with write permission
注:
fileName
指原始Excel文件的路径


基本上,我希望得到与
(桌面路径为文本)
相同的结果,但可以灵活地将文件保存到访问原始文件的任何文件夹中。

感谢您澄清您的请求。基本上,您需要在代码中添加一个“container of”行,并在新的文件路径名中使用它。如果您发布了更多的代码,我可以修改它的语法,但这应该足以让您理解它。 下面是一些示例代码,允许您选择excel文件,收集该文件的容器,提示您输入新文件名,然后允许您编写新的txt文件:

set excelFile to (choose file with prompt "Choose Excel file :" of type {"xls", "xlsx"} without invisibles)

tell application "Finder"
    set containerPath to (container of excelFile) as string
    set oldFilename to name of excelFile
end tell

set newFilename to text returned of (display dialog "Enter name of the resulting text file" default answer oldFilename)

set myFile to open for access (containerPath & newFilename & ".txt") with write permission
try
    -- add content to myFile
    write "Here's some groovy content added to the file." to myFile
    close access myFile
on error
    close access myFile
end try

对于上述解决方案,我有一些改进建议

如果使用Excel文件的“显示名称”,它将不包括文件扩展名:

set oldFilename to displayed name of excelFile
这样,您将在同一文件夹中找到“Spreadsheet.xlsx”和“Spreadsheet.txt”,而不是“Spreadsheet.xlsx.txt”

您不必像open for access那样编写自己的文本文件,因为TextEdit可以为您编写文本文件:

tell application "TextEdit"
    make new document with properties {text:"The text file contents."}
    close document 1 saving in file (containerPath & newFilename & ".txt")
end tell
这样,您就可以利用TextEdit对文本文件的复杂性。您创建了一个UTF-8文本文件,并且不存在将文件打开以进行写访问或任何其他低级磁盘错误的风险

您还可以使用TextEdit打开现有文件,在文件末尾添加文本,然后再次保存:

tell application "TextEdit"
    open file (containerPath & newFilename & ".txt")
    set the text of document 1 to the text of document 1 & return & "Some more text."
    close document 1 saving yes
end tell

我的问题是,我正在使用原始文件的路径来保存新文件。当我将路径与
打开以供访问时
,它会将原始文件名放在我的自定义参数前面。我希望我的新文件带有我选择的文件名。我编辑了这个问题以更好地反映我的意图。这有帮助吗?是的,有帮助的澄清。修订答案中的示例代码应该可以为您解决问题。