2

I had a list that read from a text file into an array but now they all have "\n" on the end. Obviously you dont see it when you print it because it just takes a new line. I want to remove it because it is causing me some hassle.

database = open("database.txt", "r")
databaselist = database.readlines()

thats the code i used to read from the file. I am a total noob so please dont use crazy technical talk otherwise it will go straight over my head

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
GavinHenderson5
  • 33
  • 2
  • 11

2 Answers2

2
"string with or without newline\n".rstrip('\n')

Using rstrip with \n avoids any unwanted side-effect except that it will remove multiple \n at the end, if present.

Otherwise, you need to use this less elegant function:

def rstrip1(s, c):
    return s[:-1] if s[-1]==c else s
uselpa
  • 18,732
  • 2
  • 34
  • 52
  • +1 for mentioning the correct way of using it in this case. Mentioning some of the side effects: using `strip()` without arguments will also remove any trailing white spaces or tabs `\t`. – skamsie Apr 02 '14 at 20:38
1

Use str.rstrip to remove the newline character at the end of each line:

databaselist = [line.rstrip("\n") for line in database.readlines()]

However, I recommend that you make three more changes to your code to improve efficiency:

  1. Remove the call to readlines. Iterating over a file object yields its lines one at a time.

  2. Remove the "r" argument to open since the function defaults to read-mode. This will not improve the speed of your code, but it will make it less redundant.

  3. Most importantly, use a with-statement to open the file. This will ensure that it is closed automatically when you are done.

In all, the new code will look like this:

with open("database.txt") as database:
    databaselist = [line.rstrip("\n") for line in database]
  • `.rstrip('\n')` in case it is a tab-delimited database with a blank field at the end (`\t\n`) – beroe Apr 02 '14 at 20:39