0

I have a list of various directories that are saved in a .txt file, and I use file.readlines() to put all the lines in that .txt file into a list.

Is there a way I could filter out the "\n" at the end of every entry?

One line in this .txt folder would look something like this

D:/Music/Song.mp3\n

I am basically taking the entries from the .txt file and putting them into a Tkinter ListBox so the user can select their song from that ListBox.

NaNdy
  • 99
  • 8

4 Answers4

0

The easiest way is to use .read().splitlines() instead of .readlines().

Chen Guevara
  • 324
  • 1
  • 4
  • 14
0

You can use python's built-in strip function, which removes the leading whitespace. For example, after you read in the file:

txtinput = D:/Music/Song.mp3\n
txtinput = txtinput.strip() # This returns the required file path without the trailing new line

Similarly, you can see How to remove \n from a list element? for more info

For more info about the strip function: https://www.programiz.com/python-programming/methods/string/strip

Joshua Foo
  • 103
  • 1
  • 9
0

Use .replace() method

string_list = [
    "D:/Music/Song.mp3\n",
    "hello world\n"
]

new_string_list = [string.replace("\n","") for string in string_list]
Luis dQ
  • 80
  • 5
0

do:

for line in file:
    directory = line.strip()

instead of using the readline() method.

with .strip() you get the line without the \n

Sven
  • 1,014
  • 1
  • 11
  • 27