0

I have these files:

actions.js - append before }

import {constants} from "./constants";

export const setUser = (value) => ({
    type: constants.SET_USER,
    payload: value,
});
//here

constants.js - append to the end

export const constants = {
    SET_USER: "SET_USER",
    //here
};

reducers.js - add a const above export and inside the combineReducers object

import {constants} from "./constants";
import {combineReducers} from "redux";
const user = (state = null, action) => action.type === constants.SET_USER ? action.payload : state;
//here
export const reducers = combineReducers({
    user,
    // here
})

And I want to add code into these files in the places where I put //here. How can I do that with Python? I know I can write over a file with open('file', 'w').write('string') but how can I actually add text without loosing and overwriting the file? I want to add the text to the existing file, not to create the file, or overwrite it. I want it to have the old text, and add the new text to it. How can I achieve this with Python?

I made it append to the actions.js like this:

import sys
import os

reducer = sys.argv[1]

open("actions.js","a").write("""export const set{reducer} = (value) => ({{
    type: constants.{constant},
    payload: value,
}});
""".format(reducer=reducer.capitalize(), constant=constant))

But I have no idea how to get the others done

3
  • Have you googled add the text to the existing file, not to create the file? Commented Apr 12, 2019 at 11:13
  • I kind of see how to append the text, but I cannot see how to add the text to the middle of the file Commented Apr 12, 2019 at 11:14
  • Read the file, slice the string at index you want, concatenate in order, and then write to the file with cursor at 0. Commented Apr 12, 2019 at 11:30

2 Answers 2

2

Read the file, slice the string at index you want, concatenate in order, and then write to the file with cursor at 0. Let x.txt be your file. "export" in the index() method here refers to a unique non repeating word. You can use unique comments to slice the string at respective positions!

with open("x.txt","r+") as f:
  old=f.read()
  print(old)

  constant_text= "What you want to add??"

  result=old[0:old.index("export")] + constant_text + old[old.index("export"):]
  # print(result)
  f.seek(0)
  f.write(result)
  print("######################################")
  print(result)

Make sure the index keywords are unique if you want to slice in multiple locations using keywords!

Here's the output

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

Comments

1

To my knowledge, this is not possible in the way you suggest in a single operation. My solution of choice would be to iterate over the file’s lines, and once you hit your // here - marker, insert the code.

new_content = ""
with open(file_name) as f:
    for line in f.readlines():
        new_content += line
        if line.strip() == "// here":
            new_content += text_to_insert

After this loop, new_content should hold the old text and the new* inserted at the right place, which you can then write to any file you like.

*assuming that your input is properly formatted, including line breaks and so on.

Comments

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.