Skip to main content
Known Participant
April 4, 2020
Answered

How to read each line of a .txt and save it in an array?

  • April 4, 2020
  • 1 reply
  • 3284 views

I need to extract each line from a text file to assign it as a variable value. Thanks in advance.

This topic has been closed for replies.
Correct answer brian_p_dts

 

 

 

 

var txt = File("path/to/file.txt");
txt.open('r');
var str = txt.read(); 
var arr = str.split('\n');

 

 

 

More on the File object and the methods and props available: https://www.indesignjs.de/extendscriptAPI/indesign-latest/#File.html There are other ways to skin the cat. You can do a while statement on !txt.eof and use txt.readln() to push a string to a fresh array, but I find split using the new line character quick and easy. You may want to set txt.encoding to 'UTF-8'. Another good practice is to check if (txt.exists) before opening it. 

1 reply

brian_p_dts
Community Expert
brian_p_dtsCommunity ExpertCorrect answer
Community Expert
April 4, 2020

 

 

 

 

var txt = File("path/to/file.txt");
txt.open('r');
var str = txt.read(); 
var arr = str.split('\n');

 

 

 

More on the File object and the methods and props available: https://www.indesignjs.de/extendscriptAPI/indesign-latest/#File.html There are other ways to skin the cat. You can do a while statement on !txt.eof and use txt.readln() to push a string to a fresh array, but I find split using the new line character quick and easy. You may want to set txt.encoding to 'UTF-8'. Another good practice is to check if (txt.exists) before opening it. 

Known Participant
April 4, 2020

Friends, another query, How do I verify that the image is inside a text frame?

var g=app.activeDocument.allGraphics;
alert("There are "+ g.length + " image ");

for (var i = 0; i < g.length; i++) {
    if (g[i].itemLink!=null && "?????????"){
    app.select(g[i].parent);
    var fp = app.selection[0].graphics[-i].itemLink.filePath;
    alert(fp);}else{
        continue;
    }
};

Carpe diem
Known Participant
April 4, 2020

I already solved it, still thanks for the previous answer. 😄

Carpe diem