Reading and Writing Text Files from Photoshop Scripts

By Josh Wright on September 2011 in tips

 

My latest posted discussed showing a UI that had textareas, buttons, and more so users could interact with your Photoshop script. But now I discovered another fun trick - reading and writing text files from JavaScript Photoshop scripts.

Reading is Fun

Not much to it - you read line by line:

var b = new File("c:\test.txt");

b.open('r');

var str = "";

while(!b.eof)

str += b.readln();

b.close();

alert(str);

So we give it a file path and it reads line-by-line until it's done. The 'r' in open('r') means we're opening the file read-only. But we can also write to that text file...

Writing is Funner

Nice title, huh? Like I said, you can write to a text file from a JavaScript Photoshop script. Just open the file with the 'w' flag. When you call file.write(...) it clears the file and writes your text. If you call it again, it appends your text. Here's an example:

var a = new File("c:\test.txt");

a.open('w');

a.writeln("hello");

a.write("world");

a.close();

The beautiful part is that now you can store data - maybe even a simple database. Or maybe you can import some comma separated goodness and throw down on some business cards. Whatever it is, Enjoy!