0

what is the pythonic way to processs "\n" in line of a file

readline or readlines or replace '\n' by myself

example file(t.txt):

221.177.0.0/16  
117.128.0.0/21  
221.183.0.0/16  

when i use the code below read the file(t.py):

import sys
fn = sys.argv[1]
lines = list()
with open(fn) as f:
    for line in f:
        lines.append(line)
print lines

when run script code, i get this output:

python t.py t.txt 
['221.177.0.0/16\n', '117.128.0.0/21\n', '221.183.0.0/16\n']

there many "\n" in list.

BertramLAU
  • 430
  • 3
  • 16

3 Answers3

2

Strip it off when processing the file.

>>> '221.177.0.0/16\n'.rstrip('\n')
'221.177.0.0/16'
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

Or you can remove the last '\n' with

    lines.append(line[:-1])

here '\n' is considered as a single character so line[:-1] would remove the trailing ONE character from "line"

manoj prashant k
  • 339
  • 1
  • 13
0

Just use rstrip in a readlines loop. For example:

import sys
fn = sys.argv[1]
f = open(fn)
lines = [l.rstrip() for l in f.readlines()]
f.close()
armatita
  • 12,825
  • 8
  • 48
  • 49
shantanoo
  • 3,617
  • 1
  • 24
  • 37