python replacing a line in a file not working

python replace whole line in file
python - replace specific line in file
python replace line in file in place
how to search and replace text in a file using python
python fileinput replace
python overwrite a specific line in a file
python replace string in file
python replace multiple lines in file

I have a JSON file named myBlock.json :

  "server": "",

I am trying to change that with new date and time info so

        with open("myBlock.json") as json_data:
            self.myBlockInfo = json.load(json_data)

        origData = self.myBlockInfo["myData"]
        origLine = '\"myData\":\"'+origData +'\",'

        nowData = self.timeISO8601ZuluUTC()
        newLine = '\"myData\":\"'+nowData+'\",'

        with open("myBlock.json", "r+") as fh:
            for line in fh.readlines():
                if origLine in line:
                    print ("1-->", line)
                    str.replace(line, origLine, newLine)
                    print("2-->", line)

but not only the line is the same but also the file myBlock.Json stays the same and does not change?

First, you do not need to escape the double quote inside single quotes. I mean, use this instead:

origLine = '"myData":"'+origData +'",'

Then, an easier way to do the replacement is to replace the whole file content instead of reading line by line:

with open("myBlock.json", "r") as fh:
    oldcontent =
    if origLine in oldcontent:
    newcontent = oldcontent.replace(origLine, newLine)
with open("newfile.json", "w") as fh:

But, this is not guaranteed to work! I put a if in the first with block to help you check if what you expect really exists. Chances are that, the input JSON can have spaces around the colon, like "myData": "foobar", or even new lines arond the colon. Those are all legitimate JSONs. That's why some one in the comment suggested you to read the JSON, modify it, and write the JSON back.

If you think writing JSON back will messed up the format, try

 newcontent = json.dumps(modified_data, indent=4)

The indent=4 will "pretty-print" your JSON by inserting appropriate indentation, likely retain some formatting you would expect.

Editing specific line in text file in Python, The reason for this is that you can't do something like "change line 2" You can only overwrite (not delete) parts of a file - that means that the new I have been practising working on files this evening and realised that I can� The fileinput module also simplifies the creation of “shell-like” tools in that if you do not supply any filenames to fileinput.input() it will read from stdin or it will read from filenames passed as command-line arguments (i.e. sys.argv[1:]) similar to how commands such as cat or sed work.

You can edit the file on this way:

with open("myBlock.json", encoding="utf-8") as json_data:
    myBlockInfo = json.load(json_data)

origData = myBlockInfo["myData"]
origLine = '\"myData\":\"'+origData +'\",'

nowData = "asdsa"
newLine = '\"myData\":\"'+nowData+'\",'
myBlockInfo["myData"] = "sdfsd"
updated =  open("myBlock.json", "w", encoding="utf-8")
json.dump(myBlockInfo, updated)

Editing the myBlockInfo["myData"] block directly and the save the file with json.dump. Also, you can use the encoding option to make sure both encodings, when read and write are the same

Python: Replacing lines in a file, Given a text file that contains a single mac address per line the goal is to process the file and replace known mac We'll start by showing the code. As you can see this code just prints the result and does not “modify” the file. import fileinput import sys def replaceAll(file,searchExp,replaceExp): for line in fileinput.input(file, inplace=1): if searchExp in line: line = line.replace(searchExp,replaceExp) sys.stdout.write(line)

What you're looking for is the indent kwarg of [Python 3]: json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw):

If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as "\t"), that string is used to indent each level.

#!/usr/bin/env python3

import sys
import json

def main(argv):
    with open("in.json") as inf:
        obj = json.load(inf)

    print("Original date:", obj["myData"])
    # Modify obj["myData"] to whatever you need (self.timeISO8601ZuluUTC())

    output_indent = int(argv[0]) if len(argv) and argv[0].isdecimal() else None
    with open("out.json", "w") as outf:
        json.dump(obj, outf, indent=output_indent)

if __name__ == "__main__":
    print("Python {:s} on {:s}\n".format(sys.version, sys.platform))


[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q055578224]> sopr.bat
*** Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ***

[prompt]> dir /b

[prompt]> type in.json
  "server": "",

[prompt]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe"
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32

Original date: 2019-04-08T15:43:05.810483Z

[prompt]> dir /b

[prompt]> type out.json
{"server": "", "name": "XYZ", "myData": "2019-04-08T15:43:05.810483Z", "someFlg": "T", "moreData": "k"}
[prompt]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" 2
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32

Original date: 2019-04-08T15:43:05.810483Z

[prompt]> dir /b

[prompt]> type out.json
  "server": "",
  "name": "XYZ",
  "myData": "2019-04-08T15:43:05.810483Z",
  "someFlg": "T",
  "moreData": "k"

As you can see, the file has been nicely rewritten without the need of modifying its raw (text) contents.

How to replace a string within a file in Python, Kite is a free autocomplete for Python developers. Code faster with the Kite plugin for your code editor, featuring Line-of-Code Completions and cloudless� In this guide, we'll be using Python version 3. Most systems come pre-installed with Python 2.7. While Python 2.7 is used in legacy code, Python 3 is the present and future of the Python language. Unless you have a specific reason to write or support Python 2, we recommend working in Python 3.

Python – How to Replace String in File?, To replace a string in File using Python, follow these steps: Open input file in read mode and handle it in text mode. Open output file in write mode and handle it in text mode. For each line read from input file, replace the string and write to output file. Close both input and output files. I use a 10-line program that solves a common problem for me — adding body { text-align: justify } to epub files that are not justify aligned. I didn't know that this line would help beforehand, I searched online for a solution and then automated the process of unzipping epub , adding the line and then packing it again.

Searching and Replacing Text in a File, Problem. You need to change one string into another throughout a file. #!/usr/ bin/env python import os, sys nargs = len(sys.argv) if not 3 <= nargs <= 5: print� Python file method next () is used when a file is used as an iterator, typically in a loop, the next () method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit. Combining next () method with other file methods like readline () does not work right.

Replace Line in Textfile, Let's say the file only contains a single word: python. How do I get the system to check the single line in the file and, if it says 'python' replace it� The connection is happening during the first execution of method in the following code , but from the second time execution of the function within the thread , the accept() function is not accepting any functoin , it just stays at the prompt and does nothing even if i connect from other local devices

  • You should read the file as a json string, load it into a dictionary, modify that dictionary with the new value, write the dictionary back to the file.
  • Yes I tried it but when I write it back all formatting is messed up
  • is what you posted the actual contents of the file? If so, that's not proper JSON
  • Could you post original and final json content? What you're trying to do here is a lame workaround (gainarie). I think it also qualifies for an XY Problem. If the file is a json read/write it as such.
  • I have edited and added more info
  • Thank you that is exactly what I had done but the format of json block changes. and becomes one complete line . { "server": "", "name":"XYZ", "myData":"2019-04-08T16:43:05.810483Z", "someFlg":"T", "moreData":"k" }