Is there an easy way to read and write specific lines from an existing txt file in python grasshopper?
Thanks in advance!
You can use the built-in open() function to open a file object, and then use the read() or write() method to read from or write to the file
# To read from a text file
with open('file.txt', 'r') as file:
data = file.read()
print(data)
# To write to a text file
with open('file.txt', 'w') as file:
file.write('Hello, world!')
Keep in mind that if the data changes while your gh is running, you have to re-read the file.
Thanks! And for example reading a specific line would be?:
with open('file.txt', 'r') as file:
data = file.readline(1)
print(data)
Yes, unfortunately I need to read/write within a python loop. I think doing it within python is easier then, right?
To read a specific line from a text file, you can use the readlines()
method to get a list of all the lines in the file, and then access the specific line by its index.
with open('file.txt', 'r') as file:
lines = file.readlines()
third_line = lines[2] #reads the 3rd line in the doc
print(third_line)
I’ve seen the Stream option in the context menu of a panel before but never tried it until now. This is a simple way to output certain results.
Could this be tweaked so streaming would be possible to an Excel file?