Open a file and edit a line












0














I'm trying to modify a specific line in a js file using python.



Here's the js file :



...
hide: [""]
...


Here's my python code :



with open('./config.js','r') as f:
lines = f.readlines()

with open('./config.js','w') as f:
for line in lines:
line = line.replace('hide', 'something')
f.write(line)


So it works but this is not what I want to do.



I want to write 'something' between the brackets and not replace 'hide'.



So I don't know how to do it: Do I have to replace the whole line or can I just add a word between the brackets?



Thanks










share|improve this question




















  • 2




    Would you try line = line.replace('hide', 'hide: ["something"]')?
    – Geno Chen
    Nov 23 '18 at 8:57
















0














I'm trying to modify a specific line in a js file using python.



Here's the js file :



...
hide: [""]
...


Here's my python code :



with open('./config.js','r') as f:
lines = f.readlines()

with open('./config.js','w') as f:
for line in lines:
line = line.replace('hide', 'something')
f.write(line)


So it works but this is not what I want to do.



I want to write 'something' between the brackets and not replace 'hide'.



So I don't know how to do it: Do I have to replace the whole line or can I just add a word between the brackets?



Thanks










share|improve this question




















  • 2




    Would you try line = line.replace('hide', 'hide: ["something"]')?
    – Geno Chen
    Nov 23 '18 at 8:57














0












0








0







I'm trying to modify a specific line in a js file using python.



Here's the js file :



...
hide: [""]
...


Here's my python code :



with open('./config.js','r') as f:
lines = f.readlines()

with open('./config.js','w') as f:
for line in lines:
line = line.replace('hide', 'something')
f.write(line)


So it works but this is not what I want to do.



I want to write 'something' between the brackets and not replace 'hide'.



So I don't know how to do it: Do I have to replace the whole line or can I just add a word between the brackets?



Thanks










share|improve this question















I'm trying to modify a specific line in a js file using python.



Here's the js file :



...
hide: [""]
...


Here's my python code :



with open('./config.js','r') as f:
lines = f.readlines()

with open('./config.js','w') as f:
for line in lines:
line = line.replace('hide', 'something')
f.write(line)


So it works but this is not what I want to do.



I want to write 'something' between the brackets and not replace 'hide'.



So I don't know how to do it: Do I have to replace the whole line or can I just add a word between the brackets?



Thanks







python






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 8:59









petezurich

3,50581734




3,50581734










asked Nov 23 '18 at 8:53









WilliamWilliam

34




34








  • 2




    Would you try line = line.replace('hide', 'hide: ["something"]')?
    – Geno Chen
    Nov 23 '18 at 8:57














  • 2




    Would you try line = line.replace('hide', 'hide: ["something"]')?
    – Geno Chen
    Nov 23 '18 at 8:57








2




2




Would you try line = line.replace('hide', 'hide: ["something"]')?
– Geno Chen
Nov 23 '18 at 8:57




Would you try line = line.replace('hide', 'hide: ["something"]')?
– Geno Chen
Nov 23 '18 at 8:57












5 Answers
5






active

oldest

votes


















4














If you want to replace text at this exact line you could just do:



with open('./config.js','r') as f:
lines = f.readlines()

with open('./config.js','w') as f:
  new_value = 'Something New'
for line in lines:
if line.startswith('hide'):
line = 'hide: ["{}"]'.format(new_value)
f.write(line)




or alternatively in the conditional



           if line.startswith('hide'):
line = line.replace('""', '"Something new"')




Here's way to replace any value in brackets for hide that starts with any spacing.



lines = '''
first line
hide: [""]
hide: ["something"]
last line
'''
new_value = 'new value'

for line in lines.splitlines():
if line.strip().startswith('hide'):
line = line[:line.index('[')+2] + new_value + line[line.index(']')-1:]
print(line)


Output:



first line
hide: ["new value"]
hide: ["new value"]
last line





share|improve this answer























  • what if hide: [""] not alone in line?
    – Andrey Suglobov
    Nov 23 '18 at 9:03








  • 1




    see the edit using str.startswith()
    – SpghttCd
    Nov 23 '18 at 9:05










  • I think that's what author meant and why I said it will replace only this exact line
    – Filip Młynarski
    Nov 23 '18 at 9:05










  • hide is alone in line
    – William
    Nov 23 '18 at 9:20










  • There is a way to change whatever there is between the brackets ? For exapme if I have "something" and the next time "somethingelse" without modifying my python code
    – William
    Nov 23 '18 at 9:27



















1














If hide: [""] is not ambiguous, you could simply load the whole file, replace and write it back:



newline = 'Something new'

with open('./config.js','r') as f:
txt = f.read()

txt = txt.replace('hide: [""]', 'hide: ["' + newline + '"]')

with open('./config.js','w') as f:
f.write(txt)





share|improve this answer































    0














    As long as you don't have "hide" anywhere else in the file, then you could just do



    with open('/config.js','r') as f:
    lines = f.readlines()

    with open('./config.js','w') as f:
    for line in lines:
    line = line.replace('hide [""]', 'hide ["something"]')
    f.write(line)





    share|improve this answer





























      0














      You can do this using re.sub()



      import re
      with open('./config.js','r') as f:
      lines = f.readlines()

      with open('./config.js','w') as f:
      for line in lines:
      line = re.sub(r'([")("])', r'1' + 'something' + r'2', line)
      f.write(line)


      It works by searching for a regular expression, but forms a group out of what you want on the left (([")) and the right (("])). You then concatenate these either side of the text you want to insert (in this example 'something').



      The bounding ( ) makes a group which can be accessed in the replace with r'1', then second group is r'2'.






      share|improve this answer































        0














        You can use fileinput and replace it inplace:



        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)

        replaceAll("config.js",'hide: [""]','hide: ["something"]')


        Reference






        share|improve this answer





















          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53443351%2fopen-a-file-and-edit-a-line%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          5 Answers
          5






          active

          oldest

          votes








          5 Answers
          5






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          4














          If you want to replace text at this exact line you could just do:



          with open('./config.js','r') as f:
          lines = f.readlines()

          with open('./config.js','w') as f:
            new_value = 'Something New'
          for line in lines:
          if line.startswith('hide'):
          line = 'hide: ["{}"]'.format(new_value)
          f.write(line)




          or alternatively in the conditional



                     if line.startswith('hide'):
          line = line.replace('""', '"Something new"')




          Here's way to replace any value in brackets for hide that starts with any spacing.



          lines = '''
          first line
          hide: [""]
          hide: ["something"]
          last line
          '''
          new_value = 'new value'

          for line in lines.splitlines():
          if line.strip().startswith('hide'):
          line = line[:line.index('[')+2] + new_value + line[line.index(']')-1:]
          print(line)


          Output:



          first line
          hide: ["new value"]
          hide: ["new value"]
          last line





          share|improve this answer























          • what if hide: [""] not alone in line?
            – Andrey Suglobov
            Nov 23 '18 at 9:03








          • 1




            see the edit using str.startswith()
            – SpghttCd
            Nov 23 '18 at 9:05










          • I think that's what author meant and why I said it will replace only this exact line
            – Filip Młynarski
            Nov 23 '18 at 9:05










          • hide is alone in line
            – William
            Nov 23 '18 at 9:20










          • There is a way to change whatever there is between the brackets ? For exapme if I have "something" and the next time "somethingelse" without modifying my python code
            – William
            Nov 23 '18 at 9:27
















          4














          If you want to replace text at this exact line you could just do:



          with open('./config.js','r') as f:
          lines = f.readlines()

          with open('./config.js','w') as f:
            new_value = 'Something New'
          for line in lines:
          if line.startswith('hide'):
          line = 'hide: ["{}"]'.format(new_value)
          f.write(line)




          or alternatively in the conditional



                     if line.startswith('hide'):
          line = line.replace('""', '"Something new"')




          Here's way to replace any value in brackets for hide that starts with any spacing.



          lines = '''
          first line
          hide: [""]
          hide: ["something"]
          last line
          '''
          new_value = 'new value'

          for line in lines.splitlines():
          if line.strip().startswith('hide'):
          line = line[:line.index('[')+2] + new_value + line[line.index(']')-1:]
          print(line)


          Output:



          first line
          hide: ["new value"]
          hide: ["new value"]
          last line





          share|improve this answer























          • what if hide: [""] not alone in line?
            – Andrey Suglobov
            Nov 23 '18 at 9:03








          • 1




            see the edit using str.startswith()
            – SpghttCd
            Nov 23 '18 at 9:05










          • I think that's what author meant and why I said it will replace only this exact line
            – Filip Młynarski
            Nov 23 '18 at 9:05










          • hide is alone in line
            – William
            Nov 23 '18 at 9:20










          • There is a way to change whatever there is between the brackets ? For exapme if I have "something" and the next time "somethingelse" without modifying my python code
            – William
            Nov 23 '18 at 9:27














          4












          4








          4






          If you want to replace text at this exact line you could just do:



          with open('./config.js','r') as f:
          lines = f.readlines()

          with open('./config.js','w') as f:
            new_value = 'Something New'
          for line in lines:
          if line.startswith('hide'):
          line = 'hide: ["{}"]'.format(new_value)
          f.write(line)




          or alternatively in the conditional



                     if line.startswith('hide'):
          line = line.replace('""', '"Something new"')




          Here's way to replace any value in brackets for hide that starts with any spacing.



          lines = '''
          first line
          hide: [""]
          hide: ["something"]
          last line
          '''
          new_value = 'new value'

          for line in lines.splitlines():
          if line.strip().startswith('hide'):
          line = line[:line.index('[')+2] + new_value + line[line.index(']')-1:]
          print(line)


          Output:



          first line
          hide: ["new value"]
          hide: ["new value"]
          last line





          share|improve this answer














          If you want to replace text at this exact line you could just do:



          with open('./config.js','r') as f:
          lines = f.readlines()

          with open('./config.js','w') as f:
            new_value = 'Something New'
          for line in lines:
          if line.startswith('hide'):
          line = 'hide: ["{}"]'.format(new_value)
          f.write(line)




          or alternatively in the conditional



                     if line.startswith('hide'):
          line = line.replace('""', '"Something new"')




          Here's way to replace any value in brackets for hide that starts with any spacing.



          lines = '''
          first line
          hide: [""]
          hide: ["something"]
          last line
          '''
          new_value = 'new value'

          for line in lines.splitlines():
          if line.strip().startswith('hide'):
          line = line[:line.index('[')+2] + new_value + line[line.index(']')-1:]
          print(line)


          Output:



          first line
          hide: ["new value"]
          hide: ["new value"]
          last line






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 23 '18 at 10:15

























          answered Nov 23 '18 at 8:57









          Filip MłynarskiFilip Młynarski

          1,5781311




          1,5781311












          • what if hide: [""] not alone in line?
            – Andrey Suglobov
            Nov 23 '18 at 9:03








          • 1




            see the edit using str.startswith()
            – SpghttCd
            Nov 23 '18 at 9:05










          • I think that's what author meant and why I said it will replace only this exact line
            – Filip Młynarski
            Nov 23 '18 at 9:05










          • hide is alone in line
            – William
            Nov 23 '18 at 9:20










          • There is a way to change whatever there is between the brackets ? For exapme if I have "something" and the next time "somethingelse" without modifying my python code
            – William
            Nov 23 '18 at 9:27


















          • what if hide: [""] not alone in line?
            – Andrey Suglobov
            Nov 23 '18 at 9:03








          • 1




            see the edit using str.startswith()
            – SpghttCd
            Nov 23 '18 at 9:05










          • I think that's what author meant and why I said it will replace only this exact line
            – Filip Młynarski
            Nov 23 '18 at 9:05










          • hide is alone in line
            – William
            Nov 23 '18 at 9:20










          • There is a way to change whatever there is between the brackets ? For exapme if I have "something" and the next time "somethingelse" without modifying my python code
            – William
            Nov 23 '18 at 9:27
















          what if hide: [""] not alone in line?
          – Andrey Suglobov
          Nov 23 '18 at 9:03






          what if hide: [""] not alone in line?
          – Andrey Suglobov
          Nov 23 '18 at 9:03






          1




          1




          see the edit using str.startswith()
          – SpghttCd
          Nov 23 '18 at 9:05




          see the edit using str.startswith()
          – SpghttCd
          Nov 23 '18 at 9:05












          I think that's what author meant and why I said it will replace only this exact line
          – Filip Młynarski
          Nov 23 '18 at 9:05




          I think that's what author meant and why I said it will replace only this exact line
          – Filip Młynarski
          Nov 23 '18 at 9:05












          hide is alone in line
          – William
          Nov 23 '18 at 9:20




          hide is alone in line
          – William
          Nov 23 '18 at 9:20












          There is a way to change whatever there is between the brackets ? For exapme if I have "something" and the next time "somethingelse" without modifying my python code
          – William
          Nov 23 '18 at 9:27




          There is a way to change whatever there is between the brackets ? For exapme if I have "something" and the next time "somethingelse" without modifying my python code
          – William
          Nov 23 '18 at 9:27













          1














          If hide: [""] is not ambiguous, you could simply load the whole file, replace and write it back:



          newline = 'Something new'

          with open('./config.js','r') as f:
          txt = f.read()

          txt = txt.replace('hide: [""]', 'hide: ["' + newline + '"]')

          with open('./config.js','w') as f:
          f.write(txt)





          share|improve this answer




























            1














            If hide: [""] is not ambiguous, you could simply load the whole file, replace and write it back:



            newline = 'Something new'

            with open('./config.js','r') as f:
            txt = f.read()

            txt = txt.replace('hide: [""]', 'hide: ["' + newline + '"]')

            with open('./config.js','w') as f:
            f.write(txt)





            share|improve this answer


























              1












              1








              1






              If hide: [""] is not ambiguous, you could simply load the whole file, replace and write it back:



              newline = 'Something new'

              with open('./config.js','r') as f:
              txt = f.read()

              txt = txt.replace('hide: [""]', 'hide: ["' + newline + '"]')

              with open('./config.js','w') as f:
              f.write(txt)





              share|improve this answer














              If hide: [""] is not ambiguous, you could simply load the whole file, replace and write it back:



              newline = 'Something new'

              with open('./config.js','r') as f:
              txt = f.read()

              txt = txt.replace('hide: [""]', 'hide: ["' + newline + '"]')

              with open('./config.js','w') as f:
              f.write(txt)






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 23 '18 at 9:19

























              answered Nov 23 '18 at 9:12









              SpghttCdSpghttCd

              4,1072313




              4,1072313























                  0














                  As long as you don't have "hide" anywhere else in the file, then you could just do



                  with open('/config.js','r') as f:
                  lines = f.readlines()

                  with open('./config.js','w') as f:
                  for line in lines:
                  line = line.replace('hide [""]', 'hide ["something"]')
                  f.write(line)





                  share|improve this answer


























                    0














                    As long as you don't have "hide" anywhere else in the file, then you could just do



                    with open('/config.js','r') as f:
                    lines = f.readlines()

                    with open('./config.js','w') as f:
                    for line in lines:
                    line = line.replace('hide [""]', 'hide ["something"]')
                    f.write(line)





                    share|improve this answer
























                      0












                      0








                      0






                      As long as you don't have "hide" anywhere else in the file, then you could just do



                      with open('/config.js','r') as f:
                      lines = f.readlines()

                      with open('./config.js','w') as f:
                      for line in lines:
                      line = line.replace('hide [""]', 'hide ["something"]')
                      f.write(line)





                      share|improve this answer












                      As long as you don't have "hide" anywhere else in the file, then you could just do



                      with open('/config.js','r') as f:
                      lines = f.readlines()

                      with open('./config.js','w') as f:
                      for line in lines:
                      line = line.replace('hide [""]', 'hide ["something"]')
                      f.write(line)






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 23 '18 at 9:04









                      DelkarixDelkarix

                      85




                      85























                          0














                          You can do this using re.sub()



                          import re
                          with open('./config.js','r') as f:
                          lines = f.readlines()

                          with open('./config.js','w') as f:
                          for line in lines:
                          line = re.sub(r'([")("])', r'1' + 'something' + r'2', line)
                          f.write(line)


                          It works by searching for a regular expression, but forms a group out of what you want on the left (([")) and the right (("])). You then concatenate these either side of the text you want to insert (in this example 'something').



                          The bounding ( ) makes a group which can be accessed in the replace with r'1', then second group is r'2'.






                          share|improve this answer




























                            0














                            You can do this using re.sub()



                            import re
                            with open('./config.js','r') as f:
                            lines = f.readlines()

                            with open('./config.js','w') as f:
                            for line in lines:
                            line = re.sub(r'([")("])', r'1' + 'something' + r'2', line)
                            f.write(line)


                            It works by searching for a regular expression, but forms a group out of what you want on the left (([")) and the right (("])). You then concatenate these either side of the text you want to insert (in this example 'something').



                            The bounding ( ) makes a group which can be accessed in the replace with r'1', then second group is r'2'.






                            share|improve this answer


























                              0












                              0








                              0






                              You can do this using re.sub()



                              import re
                              with open('./config.js','r') as f:
                              lines = f.readlines()

                              with open('./config.js','w') as f:
                              for line in lines:
                              line = re.sub(r'([")("])', r'1' + 'something' + r'2', line)
                              f.write(line)


                              It works by searching for a regular expression, but forms a group out of what you want on the left (([")) and the right (("])). You then concatenate these either side of the text you want to insert (in this example 'something').



                              The bounding ( ) makes a group which can be accessed in the replace with r'1', then second group is r'2'.






                              share|improve this answer














                              You can do this using re.sub()



                              import re
                              with open('./config.js','r') as f:
                              lines = f.readlines()

                              with open('./config.js','w') as f:
                              for line in lines:
                              line = re.sub(r'([")("])', r'1' + 'something' + r'2', line)
                              f.write(line)


                              It works by searching for a regular expression, but forms a group out of what you want on the left (([")) and the right (("])). You then concatenate these either side of the text you want to insert (in this example 'something').



                              The bounding ( ) makes a group which can be accessed in the replace with r'1', then second group is r'2'.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Nov 23 '18 at 9:08

























                              answered Nov 23 '18 at 9:02









                              slacklineslackline

                              96521032




                              96521032























                                  0














                                  You can use fileinput and replace it inplace:



                                  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)

                                  replaceAll("config.js",'hide: [""]','hide: ["something"]')


                                  Reference






                                  share|improve this answer


























                                    0














                                    You can use fileinput and replace it inplace:



                                    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)

                                    replaceAll("config.js",'hide: [""]','hide: ["something"]')


                                    Reference






                                    share|improve this answer
























                                      0












                                      0








                                      0






                                      You can use fileinput and replace it inplace:



                                      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)

                                      replaceAll("config.js",'hide: [""]','hide: ["something"]')


                                      Reference






                                      share|improve this answer












                                      You can use fileinput and replace it inplace:



                                      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)

                                      replaceAll("config.js",'hide: [""]','hide: ["something"]')


                                      Reference







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Nov 23 '18 at 9:15









                                      dalonlobodalonlobo

                                      349214




                                      349214






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.





                                          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                          Please pay close attention to the following guidance:


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53443351%2fopen-a-file-and-edit-a-line%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Sphinx de Gizeh

                                          Dijon

                                          Determine an Integral..