-1

I'm using the following code to split up a large text file into chunks of 100.

import itertools
import pprint

with open('usernames.txt') as f:
    while True:
        lines = list(itertools.islice(f, 100))  # similar to `f[0:100]`
        if not lines:
            break

        print lines

However when I print, every line has a /n of course, now I was wondering on how to rid of them.

As lines.rstrip('/n') does not work, neither does .remove().

Snowlav
  • 325
  • 1
  • 12
  • 26

2 Answers2

3

That's because /n is not an escape sequence. It is just the characters / and n. A newline in Python is represented by \n. For more information, see String literals in the documentation.

To remove the newlines from the items in the list, you can use a list comprehension:

lines = [x.rstrip('\n') for x in itertools.islice(f, 100)]
1

This might help as well:

line.replace('\n','').replace('\r','');
Greg Lafrance
  • 768
  • 1
  • 7
  • 18