Open a file and edit a line
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
add a comment |
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
2
Would you tryline = line.replace('hide', 'hide: ["something"]')?
– Geno Chen
Nov 23 '18 at 8:57
add a comment |
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
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
python
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 tryline = line.replace('hide', 'hide: ["something"]')?
– Geno Chen
Nov 23 '18 at 8:57
add a comment |
2
Would you tryline = 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
add a comment |
5 Answers
5
active
oldest
votes
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
what ifhide: [""]not alone in line?
– Andrey Suglobov
Nov 23 '18 at 9:03
1
see the edit usingstr.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
|
show 8 more comments
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)
add a comment |
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)
add a comment |
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'.
add a comment |
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
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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
what ifhide: [""]not alone in line?
– Andrey Suglobov
Nov 23 '18 at 9:03
1
see the edit usingstr.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
|
show 8 more comments
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
what ifhide: [""]not alone in line?
– Andrey Suglobov
Nov 23 '18 at 9:03
1
see the edit usingstr.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
|
show 8 more comments
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
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
edited Nov 23 '18 at 10:15
answered Nov 23 '18 at 8:57
Filip MłynarskiFilip Młynarski
1,5781311
1,5781311
what ifhide: [""]not alone in line?
– Andrey Suglobov
Nov 23 '18 at 9:03
1
see the edit usingstr.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
|
show 8 more comments
what ifhide: [""]not alone in line?
– Andrey Suglobov
Nov 23 '18 at 9:03
1
see the edit usingstr.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
|
show 8 more comments
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)
add a comment |
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)
add a comment |
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)
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)
edited Nov 23 '18 at 9:19
answered Nov 23 '18 at 9:12
SpghttCdSpghttCd
4,1072313
4,1072313
add a comment |
add a comment |
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)
add a comment |
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)
add a comment |
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)
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)
answered Nov 23 '18 at 9:04
DelkarixDelkarix
85
85
add a comment |
add a comment |
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'.
add a comment |
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'.
add a comment |
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'.
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'.
edited Nov 23 '18 at 9:08
answered Nov 23 '18 at 9:02
slacklineslackline
96521032
96521032
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
answered Nov 23 '18 at 9:15
dalonlobodalonlobo
349214
349214
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
2
Would you try
line = line.replace('hide', 'hide: ["something"]')?– Geno Chen
Nov 23 '18 at 8:57