I have ptx point cloud files, where I only need to read a line close to the start of the file.
As the files are very large, reading the whole file for this purpose is very slow.
Is there a way to read only an excerpt or a certain line from a text file in Grasshopper?
Not without custom programming. You’d have to open the file as a stream, and read it from disk until you’re done. All Grasshopper tools that read files always read the whole file.
Can you post an excerpt of such a ptx file and some info about what data you want to read from it?
Not at my computer but I’ve done it in python (if I remember correctly) with on line: open(filepath).readline(int)
Don’t know what happens in the background, but was always quit fast for me.
If I’m right it should be faster than using rhinoscriptsyntax and c# should be even faster.
Yes you can do this with a python component, for instance to get only the 4th line without reading the rest of the file:
fname = r'C:\Users\KNAPP\AppData\Roaming\McNeel\Rhinoceros\5.0\scripts\boutons\colors.txt'
with open(fname) as f:
f.readlines(3) # skip 3 lines
a = f.readline()
print a
print a.split() # split the line into a list of values
The file is automatically and safely closed after the with block, even if an error occurs during reading
Unfortunately I need to make a total newbie follow-up question, as I’m totally unfamiliar with python (…planning to get to it some day):
I can’t really understand why my text at line 10 only gets read with the ‘readlines’ set to 196 - that doesn’t seem to match any character count or the like… this is something obvious?:
No this is strange - the readlines method should skip a given number of lines. I wonder whether this has something to do with the newline character used in your file? Could it be skipping 196 bytes rather than lines? I can see no reason why it should do this… It behaves normally for me on Rhino 5 for Windows in both the rhino python editor and a Grasshopper python component.
And when I set y to 235, the script returns . That’s 39 in difference and the line does have 39 characters including the line end. So somehow this is tied to character count - the reason I said it isn’t, is because the sample here has 273 characters
Okay, this seems to work better! I think I’ll go with this for now, and start on my python later to solve the first case… Thank you so much for your help!