I want to reorder sections of lines in text file with Python
Question:
Ive got a shell file I’m opening as a text file with update commands, like this :
set line dnsConfig domain gggg.domain.com
set line dnsConfig address 9.9.9.9
set line dnsConfig isUp true
set line dnsConfig parameterAlpha 133
...
I want to reorder this like so:
set line dnsConfig isUp true
set line dnsConfig parameterAlpha 133
set line dnsConfig domain gggg.domain.com
set line dnsConfig address 9.9.9.9
...
This is just an illustration of my file(not a good one, I know), but I want to reorder only those items. I have experimented with Python’s readlines()
and looping through that way with set string parameters, but am stuck on how to move forward with this.
Answers:
this should reorder accordingly and leave the subsequent lines intact:
fname = 'test.txt'
new_lines = list()
with open(fname, 'r') as file:
lines = file.read().splitlines()
new_lines = lines
tmp = new_lines[0:4]
new_lines[0], new_lines[1] = tmp[2], tmp[3]
new_lines[2], new_lines[3] = tmp[0], tmp[1]
with open('out.txt', 'w') as new_file:
for line in new_lines:
new_file.write(line + 'n')
Get the lines from the file, reorder the ones you want, and write to the destination file — which should produce:
set line dnsConfig isUp true
set line dnsConfig parameterAlpha 133
set line dnsConfig domain gggg.domain.com
set line dnsConfig address 9.9.9.9
another line
and another
Ive got a shell file I’m opening as a text file with update commands, like this :
set line dnsConfig domain gggg.domain.com
set line dnsConfig address 9.9.9.9
set line dnsConfig isUp true
set line dnsConfig parameterAlpha 133
...
I want to reorder this like so:
set line dnsConfig isUp true
set line dnsConfig parameterAlpha 133
set line dnsConfig domain gggg.domain.com
set line dnsConfig address 9.9.9.9
...
This is just an illustration of my file(not a good one, I know), but I want to reorder only those items. I have experimented with Python’s readlines()
and looping through that way with set string parameters, but am stuck on how to move forward with this.
this should reorder accordingly and leave the subsequent lines intact:
fname = 'test.txt'
new_lines = list()
with open(fname, 'r') as file:
lines = file.read().splitlines()
new_lines = lines
tmp = new_lines[0:4]
new_lines[0], new_lines[1] = tmp[2], tmp[3]
new_lines[2], new_lines[3] = tmp[0], tmp[1]
with open('out.txt', 'w') as new_file:
for line in new_lines:
new_file.write(line + 'n')
Get the lines from the file, reorder the ones you want, and write to the destination file — which should produce:
set line dnsConfig isUp true
set line dnsConfig parameterAlpha 133
set line dnsConfig domain gggg.domain.com
set line dnsConfig address 9.9.9.9
another line
and another