0

デスクトップにファイルを書き込もうとしていますが、ファイルが見つからないというエラーがスローされます。ファイルがなくてもエラーが表示される場合は、コードにファイルを作成するように依頼しました。以下は私のコードです。

tell application "Finder"

    try
        set myFile to ("TestReport.txt")
        set logpath to (((path to desktop from user domain) as string)) as alias
        set logfile to myFile
        tell application "Finder" to make new file at (logpath) with properties {name:myFile}
    on error --file exist yet, so create it
        set logfile to myFile as alias
        display alert logfile
    end try
    try
        tell application "Finder" to make new file at ((path to desktop from user domain) as string) with properties {name:"TestReport.txt"}
        set logmsg to "File Rename"
        --set logmsg to (numberoflines as string) & ") " & tab & mylogin & tab & curDate & tab & thecount & tab & "Ver.1" & return
        set the logdata to (open for access file (logfile as text) with write permission)
        write logmsg to the logdata starting at eof
        close access logdata
        return true
    end try
end tell

ご意見をお聞かせください。ありがとう。

4

2 に答える 2

1

「エイリアス」ファイルが存在する必要があります。それがまさにそれがどのように機能するかです。したがって、ファイルへのパスが存在しない場合、「エイリアスとして」を使用するとエラーになります。もう 1 つの問題は、ファイルが既に存在する場合、Finder がファイルを作成しようとするとエラーになることです。

したがって、コードをエラーにする 2 つのことがあります。1 つはファイルが存在しない場合、もう 1 つはファイルが存在する場合です。コードは常にエラーになるため、かなり面白いです。

しかし、それは簡単な修正です。すべてのパスを文字列として保持していることに気付くでしょう。パスを使用する場合は、必要に応じて「ファイル」または「フォルダー」という単語をパスの前に置きます。これにより、文字列パスがファイル指定子に変換され、使用できるようになります。また、「エイリアスとして」を使用する必要がなくなり、文字列を追加してパス全体を形成することもできます。Finder の問題を解決するには、ファイルを作成する前にファイルが存在するかどうかを確認します。これを試して...

set myFile to "TestReport.txt"
set logpath to (path to desktop from user domain) as string
set logfile to logpath & myFile
tell application "Finder"
    if not (exists file logfile) then
        make new file at folder logpath with properties {name:myFile}
    end if
end tell
于 2013-09-17T04:45:58.193 に答える
0

これは~/Desktop/file.txt、まだ存在しない場合でも機能するはずです。

set p to (system attribute "HOME") & "/Desktop/file.txt"
set fd to open for access p with write permission
write "text" & linefeed to fd as «class utf8» starting at eof
close access fd
于 2013-09-17T04:06:43.127 に答える