python - Text file manipulation - insert a newline character after the first two characters in a line -


i have text file looks this:

xx number number number xy number number number ... xn number number number 

xx, xy etc have either 1 or 2 characters , numbers can either positive or negative, doesn't matter. figure out (but can't, life of me) how insert newline after xx, xy etc file this:

xx   number number number xy   number number number ... xn number number number 

what i'd want remove whitespaces after every xx, xy not ones between numbers. i've tried until introduces newline characters after every 2 characters. i'm super-beginner in python appreciated.

str.replace() seems choice, espcially if want modify every single line.

with open('input.txt') input_file:     open('output.txt', 'w') output_file:         line in input_file:             line = line.replace(' ', '\n', 1)             output_file.write(line) 

re.sub() choice if want modify of lines, , choice of lines modify can made regular expression:

import re open('input.txt') input_file:     open('output.txt', 'w') output_file:         line in input_file:             line = re.sub(r'(^[a-z]+)\s+', r'\1\n', line)             output_file.write(line) 

str.split() might work, also, disrupt sequence of multiple spaces between numbers:

with open('input.txt') input_file:     open('output.txt', 'w') output_file:         line in input_file:             line = line.split()             output_file.write(line[0] + '\n')             output_file.write(' '.join(line[1:]) + '\n') 

Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -