Replacing a word in a file to add another file content

Question:

Input file (csv).

NAME,TYPE,ACCESS_TOKEN
dev765,datatype,Token765
dev879,datatype,Token879

Append file:

{
  "file": "string",
  "mapping": {
    "columns": [
      {
        "type": "NAME"
      },
      {
        "type": "TYPE"
      },
      {
        "type": "ACCESS_TOKEN"
      }
    ],
    "delimiter": ",",
    "header": true,
    "update": true
  }
}

The goal is to replace the "string" in the ‘Append file’ with the content of the ‘Input file’, with line-break. So the resultant ‘Append file’ file should look like this:

{
  "file": "NAME,TYPE,ACCESS_TOKENn dev765,datatype,Token765n dev879,datatype,Token879",
  "mapping": {
    "columns": [
      {
        "type": "NAME"
      },
      {
        "type": "TYPE"
      },
      {
        "type": "ACCESS_TOKEN"
      }
    ],
    "delimiter": ",",
    "header": true,
    "update": true
  }
}

What I actually need is the first line of the ‘Append.txt’ file as:

{
  "file": "_the_content_of_the_input_file_with_n_break",
  REST OF THE FILE AS IT IS
  ....
  ....
}

I can append the entire file at the beginning or at the end if its plain text. Or replace a word with another. But just don’t know how to do with the above format and how to replace a word with an entire file.

Asked By: Fakir

||

Answers:

Try this approach.

with (open("input.csv", "r") as infile,
      open("append_file.json", "r") as append_file,
      open("output_file.json", "w") as outfile):

    infile_content = infile.read().strip()
    infile_content = infile_content.replace("n", "\n ")
    
    # You can also use the join() approach
    # infile_content = "n ".join(infile.readlines())

    append_file_content = json.load(append_file)
    append_file_content["file"] = infile_content

    json.dump(append_file_content, outfile, indent=2)

Test Code:

import json

input_file_content = """NAME,TYPE,ACCESS_TOKEN
dev765,datatype,Token765
dev879,datatype,Token879
"""

input_file_content = "n ".join(input_file_content.splitlines())

append_file_content = {
  "file": "string",
  "mapping": {
    "columns": [
      {
        "type": "NAME"
      },
      {
        "type": "TYPE"
      },
      {
        "type": "ACCESS_TOKEN"
      }
    ],
    "delimiter": ",",
    "header": True,
    "update": True
  }
}

append_file_content["file"] = input_file_content
print(json.dumps(append_file_content, indent=2))

{
  "file": "NAME,TYPE,ACCESS_TOKENn dev765,datatype,Token765n dev879,datatype,Token879",
  "mapping": {
    "columns": [
      {
        "type": "NAME"
      },
      {
        "type": "TYPE"
      },
      {
        "type": "ACCESS_TOKEN"
      }
    ],
    "delimiter": ",",
    "header": true,
    "update": true
  }
}
Answered By: Jamiu S.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.