Reputation: 35
I have a text file that looks like this:
XX number number number
XY number number number
...
XN number number number
XX, XY etc have either 1 or 2 characters and the numbers can be either positive or negative, it doesn't really matter. What I would like to figure out (but I can't, for the life of me) is how to insert a newline after XX, XY etc so that my file would look like this:
XX
number number number
XY
number number number
...
XN
number number number
What I'd also want to do is to remove the whitespaces after every XX, XY but not the ones between the numbers. Everything I've tried until now only introduces newline characters after every 2 characters. I'm a super-beginner in Python so any help would be appreciated.
Upvotes: 0
Views: 201
Reputation: 168616
str.replace()
seems like a good choice, espcially if you want to modify every single line.
with open('input.txt') as input_file:
with open('output.txt', 'w') as output_file:
for line in input_file:
line = line.replace(' ', '\n', 1)
output_file.write(line)
re.sub()
would be a good choice if you only want to modify some of the lines, and the choice of which lines to modify can be made with a regular expression:
import re
with open('input.txt') as input_file:
with open('output.txt', 'w') as output_file:
for line in input_file:
line = re.sub(r'(^[A-Z]+)\s+', r'\1\n', line)
output_file.write(line)
str.split()
might work, also, but it will disrupt any sequence of multiple spaces between the numbers:
with open('input.txt') as input_file:
with open('output.txt', 'w') as output_file:
for line in input_file:
line = line.split()
output_file.write(line[0] + '\n')
output_file.write(' '.join(line[1:]) + '\n')
Upvotes: 2
Reputation: 890
import re
with open('input.txt') as input_file:
with open('output.txt', 'w') as output_file:
for line in input_file:
splitter = re.search("\d", line).start()
output_file.write(line[:splitter].strip() + "\n")
output_file.write(line[splitter:])
Upvotes: 0