1

I have a python file named file_1.py

It has some code in which I just have to change a word: "file_1" to: "file_2" and save it as file_2.py, then again replace 'file_1' with 'file_3' and save it as file_3.py

I have to do this for say 100 times, creating 100 python files: file_1.py,file_2.py......file_100.py

I wrote a code which can replace a string, but I am stuck to write a loop which automates it. Any leads?

with open("path/to/file_1.py") as f:
content = f.read()

new_content = content.replace("file_1","file_2")

with open("path/to/file_2.py", "w") as f:
    f.write(new_content)

1 Answer 1

5

You can simply use a for loop around the replacing and writing:

with open("path/to/file_1.py") as f:
    content = f.read()

for i in range(2,101):
    new_content = content.replace("file_1","file_%s"%i)

    with open("path/to/file_%s.py"%i, "w") as f:
        f.write(new_content)

So here you repeat the process with i ranging from 2 (inclusive) to 101 (exclusive). And for each such i you .replace(..) the content such that "file1" is replaced by "file_%s"%i (the modulo % on a string here means that the %s will be replaced by the representation of i).

Then you open a file "path/to/file_%s.py"%i (again with %s being replaced by the representation of i) and you write the content to that file.

You can of course read the content of file_1 in every iteration, but I assume the content is fixed, so reading it once at the beginning of the program will be more efficient.

Sign up to request clarification or add additional context in comments.

2 Comments

what if file 1 updates quickly and before finishing writing 100 files it has already, better would be to discard writing if change detected before loop finishes
@Rico: well given the file changes a nonosecond after the program stops, that's the same problem, and then the program is not alive anymore to fix it. In my opinion it is better to make it the responsibility of the caller to ensure that contracts are valid: a bash script that would call this Python script could for instance lock the file, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.