Neil
Neil

Reputation: 6039

Inserting text in a file using Python

I have several java code file and I have to add a public class level variable in each of them. There are so many files that I need to write a python 2.2 script to do the same.

package xx.xx.xx;

import java.util.Properties;

public class MyClass extends YourClass{

    public myMethod() throws MyException {

    }
}

expected output

package xx.xx.xx;

import java.util.Properties;

public class MyClass extends YourClass{

    public static final String CO_ID = "XXXXX" 

    public myMethod() throws MyMException {

    }
}

I know file.find('{') give me the index of the first occurrence of { but I need push rest of the code down and insert my public member in each file.

Upvotes: 2

Views: 459

Answers (2)

Neil
Neil

Reputation: 6039

Ubuntu's code works but I have modified for Python 2.2 Python 2.2 compatible code

import fileinput
import sys
import re

newline = '''\
%s
    public static final String CO_ID = "XXXXX"
'''

filename = '/path/to/file.java'
for line in fileinput.input([filename], inplace=True, backup='.bak'):
    if re.match(r'public class', line):
        sys.stdout.write(newline%line)
    else:
        sys.stdout.write(line)

Upvotes: 1

unutbu
unutbu

Reputation: 879381

Python has a convenient tool for this: the fileinput module:

import fileinput
import sys
import re

newline = '''\
{l}
    public static final String CO_ID = "XXXXX"
'''

filename = '/path/to/file.java'
for line in fileinput.input([filename], inplace=True, backup='.bak'):
    if re.match(r'public class', line):
        sys.stdout.write(newline.format(l=line))
    else:
        sys.stdout.write(line)

  • inplace=True, alters the file "in-place". Actually a temporary file is created, and then moved to the original location.
  • backup='.bak' tells fileinput.input to create a backup of the original file.
  • sys.stdout.write is used instead of print since print adds an extra new line while sys.stdout.write does not.

Upvotes: 5

Related Questions