I have a number written in a text file. Is it possible to add another to the number in the text file then replace the old number with the new one? Heres my code:
set theFile to POSIX path of "Users:Tyler:Documents:File.txt"
open for access theFile
set theFileContents to read theFile
set theNewFile to run script theFileContents + 1
tell application "TextEdit"
set eof of theFileContents to 0
write theNewFile to theFileContents
if i understand your question correctly you just want to have a text file with a string and convert that string to a number then increase the value of the number by 1 write it back to the file as a string and save it boom done right ? let me know if this is what you meant.
set docsFolder to path to documents folder
set afile to "" & docsFolder & "File.txt"
open for access file afile with write permission
set oldNum to read file afile
set newString to ((oldNum as number) + 1) as string
set eof file afile to 0
log newString
write newString to file afile starting at eof
close access file afile
Related
I have a code, in which I want to loop through files in a folder, check their built-in or custom document properties (without opening them), and later open those, which are meant to be open.
To do this, I'm using Shell and to set the folder I'm using Shell.Namespace.
The problem is with the Namespace, I guess. When I use a variable strSuborCesta for the path it doesn't work. When I print the variable strSuborCesta into immediate window and use the printed string inside the Shell.Namespace("....") it does work.
By it doesn't work I mean I get:
run-time error : 91 Object variable or With block not set
when I try to loop through the files in folder (which is not set in that case, so I understand why the error occurred, but don't understand why it's not accepting a string variable)
The path is correct in both ways. But I need it to be a variable, not a hardcoded string.
Where do I error?
Is there any better way, to check document properties (like comments, title, author, etc.) without opening the Excel files?
Below is the section (currently just in testing phase) that is giving me a hard time.
str[name of variable] variables are string data types. sFile, oShell, oDir are as Variants
'--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
'get a root path
strPriecinokCesta = ThisWorkbook.Path 'path to this file
strPriecinokCesta = Left(strPriecinokCesta, Len(strPriecinokCesta) - (Len(strPriecinokCesta) - InStrRev(strPriecinokCesta, "\"))) 'root path is one level above this file
'--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
'input files are in a subfolder
strSuborCesta = strPriecinokCesta & "Zdroje\"
strSuborPripona = "Formular_BD_kotolna*.xls" 'name of a file with extension
strSuborNazov = Dir(strSuborCesta & strSuborPripona) 'actual file name
'--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
'get access to the file system
Set oShell = CreateObject("Shell.Application")
Set oDir = oShell.Namespace(strSuborCesta) '<----this will produce an error. In contrast to using a hard coded string. Why?
For Each sFile In oDir.Items '<---- run time error 91 occurs on this line
Debug.Print test & " : " & oDir.GetDetailsOf(sFile, 24) 'comments
Next
Variable strSuborNazov should be a variant
Dim strSuborNazov as variant
oShell.Namespace(strSuborNazov)
https://msdn.microsoft.com/en-us/library/windows/desktop/bb774085(v=vs.85).aspx
i'm getting a error 75 - file/path access error when i attempt to delete my file (last lines of the code block below):
' make a reference to a directory
Dim directory As New IO.DirectoryInfo(WatchDirectory) 'ex C:\Print\Realtime\
Dim directoryList As IO.FileInfo() = directory.GetFiles(WatchFilter) 'ex *.xml
Dim directoryFile As IO.FileInfo
'list the names of all files in the specified directory
For Each directoryFile In directoryList
'scans the Realtime folder (WatchDirectory) for each specified file (WatchFilter / xml) for processing.
If directoryFile.Name = RealTimeFile Then
'checks if the file is realtime by matching the name up to the ProcessRealtimeFile app setting (ex realtime.xml)
Continue For
Else
'this is not a ProcessRealtimeFile app setting (ex realtime.xml) file
Dim Name As String
Dim renameRetries As Integer = 5
'get file name without extension
Name = IO.Path.GetFileNameWithoutExtension(directoryFile.Name)
While True
Try
If File.Exists(ProcessDirectory & RealTimeFile) = False Then
'the current file to be checked against in the watch directory does not exist in the processdirectory (ex. C:\Print\Oracle\xml.rt\). continue.
Log.Write(Log.Level.Information, "RTPrint-Diamond", Environment.UserName, Environment.MachineName, "File " & directoryFile.FullName & " is being processed by scrape.")
If ArchiveXML = True Then
'copy the current file to the archive directory (ex C:\print\xml.rt\archive\), overwriting the existing file if exists
System.IO.File.Copy(directoryFile.FullName, ArchiveDirectory & directoryFile.Name, True)
End If
'update the date and time of the active file to now
System.IO.File.SetLastWriteTime(directoryFile.FullName, Date.Now)
Log.Write(Log.Level.Information, "RTPrint-Diamond", Environment.UserName, Environment.MachineName, "Date Changed.")
If ISPublisher(directoryFile.FullName) Then
'Current file is a publisher file. Process
Dim fileInfo As New IO.FileInfo(directoryFile.FullName)
Dim utf8WithoutBOM As New System.Text.UTF8Encoding(False) 'file encoding type - UTF8 w/o BOM
Using writer As StreamWriter = New StreamWriter(Path.Combine(PublisherProcessDirectory, directoryFile.Name), False, utf8WithoutBOM)
'set up write to the publisher process directory (ex C:\print5x\xml.rt\)
'publisher requires utf8 w/o BOM to read the file. We need to change the encoding type to this standard.
'this converts the file to utf8 w/o BOM to the 5x output destination
Using reader As StreamReader = fileInfo.OpenText
While Not reader.EndOfStream
Dim line As String = reader.ReadLine
writer.Write(line & vbCrLf)
End While
reader.Close()
End Using
writer.Close()
End Using
If File.Exists(Path.Combine(PublisherProcessDirectory, directoryFile.Name)) Then
'make sure the destination file was successfully re-written in utf8 w/o bom and delete the source file
If IsFileOpen(directoryFile.FullName, 1) = True Then
Microsoft.VisualBasic.FileClose(1)
End If
System.IO.File.Delete(directoryFile.FullName)
End If
I even tested with some sample solutions I read on this site to run a function test to see if the lock is present (giving error 75), and if true is returned, attempt a file close which also is not doing anything.
Obviously my writer.Close() is not doing the job. Can anyone spot why the System.IO.File.Delete(directoryFile.FullName) is not allowing me access to this text file for deletion, and how i can unlock it to delete? Is it the for each that is locking my file? I need to delete the file within the loop, so if the for loop is locking me, what are the work-arounds here?
Additionally, i tested the delete by removing the entire writer block and 2 declared variables above it, and the file still had a lock. This can help to isolate the issue to the surrounding logic and not the streamWriter portion.
Thanks in advance!
Here's a script that renames a group of files to their new filenames created in excel. It works and it's great! But the problem is if the files do not exist from the group of files the scripts ends and creates an error..
property sourceFolder : "Macintosh HD:Users:COMP1:Desktop:folder1" -- adjust as appropriate
set filenameList to read file "Macintosh HD:Users:COMP1:Desktop:renamethis.txt" using delimiter {return}
set {oldDelims, text item delimiters} to {text item delimiters, tab}
tell application "Finder"
repeat with aFile in filenameList
set codified_name to (sourceFolder & ":" & (text item 1 of aFile)) as string
set real_name to text item 2 of aFile
set name of file codified_name to real_name
end repeat
end tell
I asked around for some help and they gave me this code to add. The problem is I do not know how and where to add this code and how to define it. I want to be able to create a .txt file that contain the files not renamed instead of stopping the whole script.
try
set name of file codified_name to real_name
on error error_string number error_number
write error_string to log_file_handle starting at eof
end
I don't really know how to code and just rely on posts from the internet and try to tweak them. So if anyone can help me..that would be really really awesome!
Here, this shows how to add a try block into your code above. You needed more code to write to an error log file as well. Should be enough to go on:
property sourceFolder : "Macintosh HD:Users:COMP1:Desktop:folder1" -- adjust as appropriate
set log_file_path to "Macintosh HD:Users:COMP1:Desktop:myErrorLogFile.txt"
set {oldDelims, AppleScript's text item delimiters} to {AppleScript's text item delimiters, tab}
try
set filenameList to read file "Macintosh HD:Users:COMP1:Desktop:renamethis.txt" using delimiter {return}
tell application "Finder"
repeat with aFile in filenameList
set codified_name to (sourceFolder & ":" & (text item 1 of aFile)) as string
set real_name to text item 2 of aFile
set name of file codified_name to real_name
end repeat
end tell
set AppleScript's text item delimiters to oldDelims
on error error_string number error_number
set AppleScript's text item delimiters to oldDelims
set log_file_handle to (open for access file log_file_path with write permission)
write ((current date) as string) & tab & error_string to log_file_handle starting at eof
close access log_file_handle
end try
I am trying to make a simple counter that adds one to the count every time the script is run. I have tried using a property but that doesn't work because it resets whenever the script is edited or the computer is turned off. Here is the code I have that I took from here.
set theFile to ":Users:hardware:Library:Scripts:Applications:LightSpeed:" & "CurrentProductCode.txt"
open for access theFile
set fileContents to read theFile
close access theFile
set counter to fileContents as integer
on add_leading_zeros(counter, max_leading_zeros)
set the threshold_number to (10 ^ max_leading_zeros) as integer
if counter is less than the threshold_number then
set the leading_zeros to ""
set the digit_count to the length of ((counter div 1) as string)
set the character_count to (max_leading_zeros + 1) - digit_count
repeat character_count times
set the leading_zeros to (the leading_zeros & "0") as string
end repeat
return (leading_zeros & (counter as text)) as string
else
return counter as text
end if
end add_leading_zeros
add_leading_zeros(counter, 6)
open for access newFile with write permission
set eof of newFile to 0
write counter + 1 to newFile
close access newFile
With this I get the error:
Can’t make ":Users:hardware:Library:Scripts:Applications:LightSpeed:CurrentProductCode.txt" into type file.
If I add "set theFile to theFile as alias" after the first "open for access theFile" it gets a little further in the code, but gets another error:
Can’t make "1776" into type integer.
And now I am out of ideas. I have googled all over the place haven't found anything that works for me. Thanks
I like to use script objects to store data:
set thePath to (path to desktop as text) & "myData.scpt"
script theData
property Counter : missing value
end script
try
set theData to load script file thePath
on error
-- On first run, set the initial value of the variable
set theData's Counter to 0
end try
--Increment the variable by 1
set theData's Counter to (theData's Counter) + 1
-- save your changes
store script theData in file thePath replacing yes
return theData's Counter
I've written a data sorter which writes out a .build extension to the files it's writing to so nothing tries to lift it as it's writing data to particular files.
At the end, I want to rename anything with a .build extension to a .dat before the program closes.
For Each f In outputFiles
For Each r In TrailerRecords
' Set the bill count variable
If r.VariableField Then
r.Fields(1) = String.Format("{0:000000}", f.Value)
End If
' Write the trailer record to the output file
File.AppendAllText(f.Key, r.ToString() & vbLf)
Next
' Rename all.build files to .dat
NEEDS TO GO HERE
' Copy each output file to the backup directory
File.Copy(f.Key, Path.Combine(backupFolder, Path.GetFileName(f.Key)), True)
Next
End Sub
Get the files and rename it:
Dim auxFile as String
Dim files() As String = IO.Directory.GetFiles(myFolderPath, "*.build")
For Each sFile As String In files
auxFile = IO.Path.GetFileNameWithoutExtension(sFile) & ".dat"
My.Computer.FileSystem.RenameFile(sFile, auxFile)
Next
You can use File.Copy() with the overwrite property to True instead.
Take a look at the MSDN documentation:
GetFiles
RenameFile
Copy
GetFilenameWithoutExtension