0

I have to read a txt file with for example this:

test
test2
test3
test4

If I use a this code

read_of_string = open("mylink.txt", "r")
read_of_string = read_of_string.readlines()
print(read_of_string)

a output is ["test/n","test2/n","test3/n","test4/n"]

if I use this code

print(read_of_string[0])

output is "test" (enter)

I have to append it into a

listofstring = []
listofsting.append(read_of_string)

it is not working Output should be a list with strings without enters like

["test","test2","test3","test4"]

2 Answers2

0

How does this work?

a = ["test\n","test2\n","test3\n","test4\n"]
b = [item.rstrip() for item in a]
print(b)
['test', 'test2', 'test3', 'test4']
MattiH
  • 554
  • 5
  • 9
-1

Simply use the str.splitlines() method:

read_of_string = read_of_string.read().splitlines()

So in your code, it should be:

read_of_string = open("mylink.txt", "r")
read_of_string = read_of_string.read().splitlines()
print(read_of_string)

But do note that it is a better practice to use the with handler to open files:

with open("mylink.txt", "r") as r:
    read_of_string = r.read().splitlines()
    print(read_of_string)
Red
  • 26,798
  • 7
  • 36
  • 58