Question: I am a python newbie and would like help with the following task:

Given a h/cpp file i would like to replace each #define line with static const.
Of course the type of the variable should be correct (lets say only int or string).

How can i do that?

Answer: 
```
new = ""
file = open("file.cpp")
for line in file:
    if "#define" in file:
        splitline = line.split(" ")
        new += "static const "
        if '"' in line:
            new += "string "
        else:
            new += "int "
        new += splitline[1]
        new += " = "
        new += splitline[2]
        new += ";\n"
    else:
        new += line + "\n"
file.close()
newfile = open("new.cpp")
newfile.write(new)

```
```
import sys

# Read in the file as an array of lines
lines = file(sys.argv[1], 'r').readlines()

# Loop over the lines and replace any instance of #define with 'static const'
for line_no in xrange(len(lines)):
    lines[line_no] = lines[line_no].replace('#define', 'static const')

# Write the file back out
file(sys.argv[1], 'w').writelines(lines)

```

And, yes, you could replace my loop with a list comprehension, but for someone new to Python, this is more clear. The list comprehension version is:

```
lines = [line.replace('#define', 'static const') for line in file(sys.argv[1], 'r').readlines()]
file(sys.argv[1], 'w').writelines(lines)

```

Now these example don't take the type into account, but this automatically replacing things like this is probably a terrifying prospect. You should really look to see that what you're doing is actually correct, using a text editor as someone else pointed out, but in general this is how you search and replace.

Alternative implementations will use regular expressions. For that you will import the re module.