excelmacosapplescriptapplescript-objc

Applescript: Write New File Without Old Filename


To preface: My Applescript takes an Excel file, and copies its data into a new plain text file.

I am having trouble writing the new text file in the same location as my existing Excel file, but without the filename of the original file.

For example: My Excel file is "FilenameA.xls" and when I save my new text file, it saves it as "FilenameA.xlsFilenameB.txt"

How can I save this new file to the same location, but with my own filename?

NOTE: It works when I use (path to desktop as text) but I won't always be saving these to my desktop.

set myFile to open for access (path to desktop as text) & blahBlah & ".txt" with write permission

When I try the script below, it gives me the original filename PLUS my new file name.

set myFile to open for access (fileName) & blahBlah & ".txt" with write permission

NOTE: fileName refers to the path of the original Excel file.

Essentially I want the same results as (path to desktop as text) but with the flexibility of saving the file to whatever folder in which the original was accessed.


Solution

  • Thank you for clarifying your request. Basically, you needed to add a "container of" line in your code, and use that in the new file path name. If you posted more of you code, I could adapt its syntax in place, but this should be enough for you to figure it out. Here's some sample code that allows you to select an excel file, collects the container of that file, prompts you for a new filename, and then allows you to write the new txt file:

    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