0

I want to read a file in python and put each new line into an array. I know how to do it in PHP, with the file(fn, FILE_IGNORE_NEW_LINES); function and it's FILE_IGNORE_NEW_LINES parameter, but how do I do it in Python?

George
  • 2,371
  • 4
  • 13
  • 15

3 Answers3

1

When reading a file (line-by-line), usually the new line characters are appended to the end of the line, as you loop through it. If you want to get rid of them?

with open('filename.txt', 'r') as f:
    for line in f:
        line = line.strip('\n')
        #do things with the stripped line!
aIKid
  • 26,968
  • 4
  • 39
  • 65
0

This is the same as (In Python):

with open("file.txt", "r") as f:
    for line in f:
        line = line.rstrip("\n")
        ...
James Mills
  • 18,669
  • 3
  • 49
  • 62
  • No, no it's not. `FILE_IGNORE_NEW_LINES` strips newline characters from the ends of the strings. `FILE_SKIP_EMPTY_LINES` skips empty lines. Also, `if not line` is backward, and it won't work anyway since the lines all have newline characters on them. – user2357112 Dec 11 '13 at 01:43
  • Noted (*I'm not a PHP Developer*). Updating my answer... – James Mills Dec 11 '13 at 01:44
0

You want this:

with open('filename.txt', 'r') as f:
    data = [line.replace('\n', '') for line in f]
Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94
  • That would load the whole file, wouldn't it? – aIKid Dec 11 '13 at 01:42
  • ``f.readlines()`` will read in the entire file. Yes. – James Mills Dec 11 '13 at 01:43
  • 1
    You don't need the `f.readlines()` call. That creates an unnecessary additional list. You can just use `for line in f`. – user2357112 Dec 11 '13 at 01:44
  • would `data = [line.strip() for line in f]` do the trick as well? (no need to read all lines an extra time with `readlines` and `.strip()` takes care of `\r\n` or other line-enders, as seen on windows systems, for example) – inspectorG4dget Dec 11 '13 at 01:45
  • Not if non-newline whitespace at the start or end of a line is significant. Also, opening the file in text mode should take care of newline conversion, or universal newlines mode if you want to handle mixed newline types in a single file. – user2357112 Dec 11 '13 at 01:46
  • @user2357112 -- In that case, you could use `line.rstrip('\n')` – mgilson Dec 11 '13 at 01:51