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

Time:01-17

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

version: 1

dn: cn=1234,ou=users,ou=system
sn: [email protected]
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:-

version: 1

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

dn: cn=1234,ou=users,ou=system
sn: [email protected]
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?

CodePudding user response:

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))
  •  Tags:  
  • Related