How to Stop Editor Replace (Python Script) from Inserting New Lines?
-
Hello everyone, it’s me again!
How do I find and replace using this script without inserting new lines or retain the original format?
The Script:with open("C:\Users\Mayonnaisu\Desktop\New folder\Test.txt") as f: for l in h: s = l.split("*") editor.replace(s[0], s[1])
Test.txt
let's*why see*the it*how
The File:
let's see it see
The Output:
why the how the
The Desired One:
why the how the
Could anyone help me?
Thanks in advance! -
A line by definition (at least my definition) always has a line-ending character(s) included. Thus, when you get a line (
l
) from your file withfor l in h:
(which, where didh
come from as your file object isf
??), yourl
variable will, for the first line, contain:let's*why\r\n
So from there it is easy to see why you get extra lines in your output, isn’t it? Your
s[0]
will belet's
ands[1]
will bewhy\r\n
. This assumes the typical Windows line-ending of\r\n
(carriage return + line feed).The way I do such a section of code is:
with open('test.txt') as f: for line in f: line = line.rstrip() # <-- the key change from how OP is doing it! # ...
The
.rstrip()
removes whitespace from the end of theline
string. If you want to be really “safe” and only remove line-ending characters, change it to.rstrip('\n\r')
. (Whitespace is defined as more than line-ending characters).BTW, this is really a Python question, not a PythonScript question.
-
@Alan-Kilborn
So that’s how it is. At first I tried to add.strip("\n")
afterl.split("*")
, but that caused the script to stop at the first replacement or stopped working altogether (I forget which one because I tried some things). I did it wrongly after all.
Now that I think about it why would I write “h” as the object lol. Then again, unlike in Python IDLE, I was not given any error warning for such a mistake. Anyway, thanks a lot! -
@Mayonnaisu said in How to Stop Editor Replace (Python Script) from Inserting New Lines?:
I was not given any error warning for such a mistake.
So perhaps you had it defined as
h
while you were developing your script. You did a few runs…h
got redefined a few times. Then you changed it and got rid ofh
as you are debugging. The reason it might not flag a subsequent run with an error, is thath
is still defined, from a previous run! You could get your script finalized (so you think), and it tests perfectly. Then you shut Notepad++ down, sleep, and restart N++ the next day, and use your script, to get an error like this one:This is a “problem” with script commands run with global scope. Variables from earlier runs can be used in new runs. Either don’t execute script commands so that they set variables in the global namespace (use
def main():
andmain()
…) or, before deciding you are finished with a script, exit N++, restart N++, and test your script again. -
@Alan-Kilborn
Oh, you’re right! Thanks again!