Reading and Writing Text Files from Photoshop Scripts

48 sec read

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");</p>
<p>b.open('r');</p>
<p>var str = "";</p>
<p>while(!b.eof)</p>
<p>str += b.readln();</p>
<p>b.close();</p>
<p>alert(str);</p>
<p>

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");</p>
<p>a.open('w');</p>
<p>a.writeln("hello");</p>
<p>a.write("world");</p>
<p>a.close();</p>
<p>

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!

Leave a Reply

Your email address will not be published. Required fields are marked *