0

I have encountered a very strange problem with 'txt' file in ubuntu, I have a txt file that when reads from windows with python command open('file.txt','r').readlines(), it gives \n of each end of line, but when I read it on ubuntu machines with the same open('file.txt','r').readlines(), it gives \r\n endings, what's the problem?(I expected the \n ending)

==EDIT==

Just to make it clear, because most people link some question like 'what is \r and what is \n'. That's not the problem here.

The problem is as follows:

  • You have a file, let's say file.txt
  • Read the file (using Python) on windows and it produces \n line endings
  • Read (supposedly) the same file (using Python) on linux and it produces \r\n line endings
  • Isn't it counter-intuitive?
Piotr Kamoda
  • 956
  • 1
  • 9
  • 24
K.Wanter
  • 969
  • 3
  • 14
  • 30
  • Possible duplicate of [Dealing with Windows line-endings in Python](http://stackoverflow.com/questions/2717086/dealing-with-windows-line-endings-in-python) – Sebastian Wozny Feb 27 '17 at 12:23
  • Text files created on DOS/Windows machines have different line endings than files created on Unix/Linux. DOS uses carriage return and line feed ("\r\n") as a line ending, which Unix uses just line feed ("\n"). This is answered plenty of times already in the forum. – Vijayakumar Udupa Feb 27 '17 at 12:25
  • @SebastianWozny I doubt that's a duplicate, because question tells us that it's the opposite situation from what we would expect. – Piotr Kamoda Feb 27 '17 at 12:25
  • Do you use any ftp client? – Piotr Kamoda Feb 27 '17 at 12:28
  • To understand that you need to go through this link – Rajshekhar Horatti Feb 27 '17 at 12:28
  • @RajshekharHoratti again I recommend to read the question with understanding – Piotr Kamoda Feb 27 '17 at 12:30
  • 1
    The Python runtime on windows will just take care of it and represent it correctly as `\n` wihle the ubuntu runtime won't. – Sebastian Wozny Feb 27 '17 at 12:30
  • 1
    You can use open().read().splitlines() instead to avoid dealing with different line endings – Baryo Feb 27 '17 at 13:06
  • In Python 2, if you want Linux to automatically handle reading Windows CRLF newlines you need to explicitly request universal newlines in the `open` mode arg, as mentioned in [the docs](https://docs.python.org/2/library/functions.html#open), and your Python has to be built with universal newlines support (it usually is). – PM 2Ring Feb 27 '17 at 13:36

0 Answers0