Home > database >  How to write in a dat file in python
How to write in a dat file in python

Time:11-17

I have this content in a dat file I can access easily, it's not at the beggining of the file but in the middle. I insert only the part of the file that I need to modify.

{
  ....,
    "Rot": {
      "RM": [
        ",>=,",
        ",>=,",
        ",>=,",
        ",>=,",
        ",>=,",
        ",>=,",
        ",>=,",
        ",>=,",
        ",>=,",
        ",>=,",
        ",>=,",
        ",>=,",
        ",>=,",
        ",>=,",
        ",>=,",
        ",>=,",
        ",>=,",
        ",>=,",
        ",>=,",
        ",>=,"
      ]
    },
  .......        
}

Instead of a line with ",>=,", I wish I could insert a custom string like for example "M,<=,5", from python code, as I would have to do this on many files/many times. I can read the file through this script, but I don't understand how to find the line I want to change in the python code and how to overwrite in it the string of my interest.

prefixed = [filename for filename in os.listdir('.') if filename.startswith("CRY")] #NQ, DIV, ecc..
for i in range(len(prefixed)):
    with open(prefixed[i], 'r') as file:
        lines = file.readlines()
        print(lines)

CodePudding user response:

prefixed = [filename for filename in os.listdir('.') if filename.startswith("CRY")] #NQ, DIV, ecc..
for i in range(len(prefixed)):
    # Read lines
    file = open(prefixed[i], 'r')
    file_content = file.readlines()
    file.close()

    # Treatment
    for pos, line in enumerate(file_content):
        if ",>=," in line:
            file_content[pos] = line.replace(",>=,", "myCustomString")

    # Write lines
    file = open(prefixed[i], 'w')
    file.writelines(file_content)
    file.close()

To modify only the first element:

prefixed = [filename for filename in os.listdir('.') if filename.startswith("CRY")] #NQ, DIV, ecc..
for i in range(len(prefixed)):
    # Read lines
    file = open(prefixed[i], 'r')
    file_content = file.readlines()
    file.close()

    # Treatment
    for pos, line in enumerate(file_content):
        if ",>=," in line:
            file_content[pos] = line.replace(",>=,", "myCustomString")
            # Add break to quit loop after first replacement
            break

    # Write lines
    file = open(prefixed[i], 'w')
    file.writelines(file_content)
    file.close()
  • Related