Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to cut some lines from a file and paste them at certain position in a same file using python?

I have a file named ‘test.ldif’ that contains some text as follows:

version: 1

dn: cn=1234,ou=users,ou=system
sn: test@gmail.com
cn: 1234
objectClass: top
objectClass: iPerson
objectClass: person
objectClass: oPerson
 =
uid: test1

dn: ou=users,ou=system
ou: users
objectClass: top
objectClass: Unit

dn: cn=iproxy,ou=users,ou=system
sn: iproxy
cn: iproxy

I want to cut the lines-

dn: ou=users,ou=system
ou: users
objectClass: top
objectClass: Unit

And, paste them at the top after version: 1 as following:-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

version: 1

dn: ou=users,ou=system
ou: users
objectClass: top
objectClass: Unit

dn: cn=1234,ou=users,ou=system
sn: test@gmail.com
cn: 1234
objectClass: top
objectClass: iPerson
objectClass: person
objectClass: oPerson
 =
uid: test1

dn: cn=iproxy,ou=users,ou=system
sn: iproxy
cn: iproxy

I want to do cut-paste operations in the same file using python. How can I achieve the same?

>Solution :

I think you were overthinking this. It’s not a hard problem.

parts = open('x.txt').read().split('\n\n')
parts.insert( 1, parts.pop(2))
print('\n\n'.join(parts))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading