Hi,
I have wrote and trying to implement the code. I want to replace the whole lline containing anything like mov9, inp9 etc.
filename = 'myfile.txt'
with open(filename, 'r') as f:
text = f.read()
text = text.replace('mov9=', 'mov9=this is')
text = text.replace('inp9=go', 'nom')
text = text.replace('nin9', 'ten9=pop')
with open(filename, 'w') as f:
f.write(text)
when I run the code..I got the output like 'mov9=this is' first time. But second time I got like' mov9=this is this is'. I just want to replace the whole line containing move9 or inp9 everytime.
Please help me.
Go line by line:
filename = 'myfile.txt'
new_lines = []
with open(filename, 'r') as f:
for line in f:
if 'mov9=' in line:
new_lines.append('mov9=this is')
elif 'inp9=go' in line:
new_lines.append('nom')
elif 'nin9' in line:
new_lines.append('ten9=pop')
else:
new_lines.append(line)
with open(filename, 'w') as f:
f.write('\n'.join(lines))
Thanks.
I see f.write('\n'.join(lines))
When I compile lines is not found. Is this is 'new_lines'?
If I put the 'new_lines' then the file delete all.
filename = 'myfile.txt'
new_lines = []
with open(filename, 'r') as f:
for line in f:
if 'mov9=' in line:
new_lines.append(line.replace('mov9=', 'mov9=this is'))
elif 'inp9=go' in line:
new_lines.append(line.replace('inp9=go', 'nom'))
elif 'nin9' in line:
new_lines.append(line.replace('nin9', 'ten9=pop'))
else:
new_lines.append(line)
with open('output.txt', 'w') as f:
f.write('\n'.join(new_lines))
Yes, that should be new_lines. in the last line, not lines.
Thanks. One thing.
I just want to write in same myfile.txt file, not the output.txt file.
(Aug-15-2019, 09:57 PM)mdalireza Wrote: [ -> ]I just want to write in same myfile.txt file, not the output.txt file.
There is
fileinput in standard library or cleaner use
in-place.
import in_place
filename = 'myfile.txt'
new_lines = []
with in_place.InPlace(filename) as f:
for line in f:
if 'mov9=' in line:
new_lines.append(line.replace('mov9=', 'mov9=this is'))
elif 'inp9=go' in line:
new_lines.append(line.replace('inp9=go', 'nom'))
elif 'nin9' in line:
new_lines.append(line.replace('nin9', 'ten9=pop'))
else:
new_lines.append(line)
f.write(''.join(new_lines)
(Aug-15-2019, 09:57 PM)mdalireza Wrote: [ -> ]Thanks. One thing.
I just want to write in same myfile.txt file, not the output.txt file.
Then change the code to do so. What´s the problem in doing so?
I changed it to "output.txt" so that you have your original and the new file
and can compare it visually if the code is doing what you want.
Hi,
I am trying to write to a list from value from optionmenu. But I am keep getting 'AttributeError: 'tuple' object has no attribute 'get''. Please help
mOption1 = ["True", "False"]
mOpvar1 = tk.StringVar()
mOpvar1.set("True")
# mOpvar1.trace_add('write', self.writevalue)
widget=tk.OptionMenu(self, mOpvar1, *mOption1)
widget.place(x=d+380, y=j+30)
print (widget)
def callback(*args):
dd = mOpvar1.get()
self.widgets.append(args)
mOpvar1.trace('w', callback)