0

I have some data and I am trying to read a txt file and read it line by line in excel by implementing a specific column number. For example:

0.12345 0.14251 0.12155...... 0.25541

And say after filling up 1000th column I want to put the next data into the next line:

0.12345 0.14251 0.12155...... 0.25541
0.15845 0.17151 0.19255...... 0.23572

I understand that if I have some kind of string (eg.~) after that number I want to split, this could be done using data.split like so:

data = testingdata.readline()   #reading a line from the .txt file 
data = data.split("~") #filter the ~ and put that into the next row 

But in this case, I only know the column number I want to split rather than a known string. How could I possibly implement the same method here?

Thank you so much in advance for help!

swiftlearneer
  • 324
  • 4
  • 17

1 Answers1

0

Here is a solution that allows you to split a string by specific number of columns. Hopefully you can adapt this code to your needs. I got the idea from here: Is there a way to split a string by every nth separator in Python?.

s = '1 2 3 4 5 6 7 8 9 10'
delimiter = ' '
n = 3

numbers = s.split(delimiter)
group_indices = range(0, len(numbers), n)
rows = [delimiter.join(numbers[i:i+n]) for i in group_indices]
print(rows)

Output:

['1 2 3', '4 5 6', '7 8 9', '10']

Once you have a list of rows, you can do whatever you want with them. For example:

text_block = '\n'.join(rows)
print(text_block)

Output:

1 2 3
4 5 6
7 8 9
10
DV82XL
  • 5,350
  • 5
  • 30
  • 59