-1

I have the following file, input.txt

= TITLE =
{{{
Leave Alone
}}}

{{{
Change Me First
}}}

{{{
Change Me second
}}}

And Python Code

obj = file("input.txt")
for i in obj:
    i = i.replace("\n", "")
    if i == "{{{":
        print i
    else:
        pass

The problem is if I copy and paste the text into Windows Notepad, upload the file to a linux server and run the script, nothing happens. If I copy and paste the text right into Vi on the server and save input.txt, it works as expected.

I know Windows and *nix text editors handle newlines differently (Windows files show extra new lines on Linux and Linux Files all show up as one line on Windows notepad), could this be part of the problem?

user324747
  • 255
  • 3
  • 16
  • 1
    It's because of the `\n` vs the `\n\r` issue with Windows. – cs95 Jul 03 '17 at 00:44
  • If I add the line `i = i.replace("\n", "")` then it prints without extra lines – user324747 Jul 03 '17 at 00:45
  • Yeah. Windows adds those carriage returns. – cs95 Jul 03 '17 at 00:46
  • It is not clear to me what do you want the code to do. You say: *"...nothing happens. If I copy and paste the text right into Vi on the server and save input.txt, it works as expected."* What do you expect to happen? – AGN Gazer Jul 03 '17 at 00:47
  • I want to match the lines with `{{{` The Linux file prints the line but not the Windows file. – user324747 Jul 03 '17 at 00:49
  • 1
    [How can I remove (chomp) a newline in Python?](https://stackoverflow.com/q/275018/608639) It should handle Linux `LF`, OS X `CR` and Windows `CR-LF`. Once you agnostically read the line, then match it. Historically, `CR-LF` pairs have been traditionally used in RFCs like FTP and Email. They are among the oldest RFCs used by the internet community. – jww Jul 03 '17 at 00:51
  • OK I'll look at rstrip – user324747 Jul 03 '17 at 00:55

1 Answers1

1

Do you really need to "strictly" replace ending \n with empty string? I would suggest that you replace the line in your code:

i = i.replace("\n", "")

with

i = i.rstrip() # or i.rstrip('\r\n')
AGN Gazer
  • 8,025
  • 2
  • 27
  • 45
  • I originally thought to use strip but thought it might mess up space characters, but I think it's split() that affects all whitespace (newline and spaces) not strip. What is the difference between strip() and rstrip()? – user324747 Jul 03 '17 at 01:07
  • 1
    `rstrip()` removes white spaces from the right side (end) of the string. `strip()` removes white spaces from both left (beginning) and right (end) sides of the string. – AGN Gazer Jul 03 '17 at 02:00