Page 1 of 1
insert line into tekst file
Posted: February 27th, 2005, 8:27 am
by mads
I would like to write a script that edits itself.
So I can Save the choises I make in the UI .
Now I´m creating another tekstfile, but is it possible to edit the script itself?
if I do this:
var myScript = new File("myScript.jsx");
myScriptVar.open("e");
myScriptVar.writeln("new line");
myScriptVar.close();
it replace the first line with "new line"
and as the first line ,and it replaces the next with a blank line, but it also delete one line of code.
so If I use it enough it will delete the entire script
what to do?
-mads
Posted: March 13th, 2005, 11:24 am
by Paul Tuersley
I've found that the safest way to edit an existing text file is to read the whole file, change it, and then rewrite it. Here's an example of this:
Code: Select all
{
// define a new file in same directory as the script.
testFile = new File("readwritetest.txt");
// open file for writing
testFile.open("w", "TEXT", "????");
testFile.writeln("banana");
testFile.writeln("peach");
testFile.writeln("apple");
testFile.writeln("orange");
testFile.close();
// will use these variables to store whole text file in 2 sections
// either side of the search string
var textBefore = "";
var textAfter = "";
// open file for reading
testFile.open("r");
// look for search string until we reach the end of the file
// storing all the text in the process
while(testFile.tell() < testFile.length) {
currentPos = testFile.tell();
theLine = testFile.readln()
alert("At byte " + currentPos + " in file, line is " + theLine);
// if it isn't the search string, add to the textBefore variable
// also add a line return
if (theLine != "apple") {
textBefore += theLine + "\r";
} else {
// otherwise, define foundString and store rest of file
alert("found apple, will replace with pear");
foundString = theLine;
while(testFile.tell() < testFile.length) {
currentPos = testFile.tell();
theLine = testFile.readln()
alert("At byte " + currentPos + " in file, line is " + theLine);
textAfter += theLine + "\r";
}
}
}
testFile.close();
// now completely rebuild the original file, inserting the replacement
// for the search string
testFile.open("w");
testFile.write(textBefore + "pear\r" + textAfter);
testFile.close();
}
After running the script, check the newly created file "readwritetest.txt" in the same folder as the script and you'll see that the line "apple" has been replaced by "pear".
You may also find this link useful:
http://aczet.free.fr/phpBB2/viewtopic.php?t=157
You said that you wanted to save choices that you made in the scripts UI? In which case another possibility is that you could save these settings in the After Effects preferences. You can create custom prefs using the following code:
Code: Select all
{
var username = "mads";
app.settings.saveSetting("mads_prefs", "UserName", username);
if (app.settings.haveSetting("mads_prefs", "UserName")) {
theUser = app.settings.getSetting("mads_prefs", "UserName");
alert(theUser);
}
}