2

I open a text file, now each element in the text file is separated by a line break. when I use readlines() It keeps this line break in the list, this is after each element so as it looks like this [zebra\n, ant\n,] i was wondering whether there is a easy function or piece of coding that I could use to just strip all the elements of this line break!

this is the code i have written so far

filelist=file.readlines()
file.close()
return filelist
Eric
  • 95,302
  • 53
  • 242
  • 374
Charlie Hardy
  • 175
  • 1
  • 3
  • 14

1 Answers1

2

try:

filelist = [line.rstrip('\n') for line in file]
Jim Garrison
  • 4,199
  • 4
  • 25
  • 39
  • 'filelist=file.readlines() file.close() return filelist' this is what i have written so far how would i implement it in to this? – Charlie Hardy Jan 26 '13 at 09:58
  • which one, this is what ive written so far ` for line in file.readlines(): line.rstrip('\n') filelist=file.readlines() file.close()` – Charlie Hardy Jan 26 '13 at 10:15
  • it just prints blank when i do it if i remove either of them and even when i put them back it prints nothing – Charlie Hardy Jan 26 '13 at 10:17