1
file = open("file path", "r") 
links = file.read().split("\n")
print(links)

looks like this ['https://www.youtube.com/channel/UCWTgK00SCKKNgpbsAgqzUxw/videos','https://www.youtube.com/watch?v=4Dkl1K3mtHM', '']

I want it to be like this: ['https://www.youtube.com/channel/UCWTgK00SCKKNgpbsAgqzUxw/videos','https://www.youtube.com/watch?v=4Dkl1K3mtHM']

How can I achieve this? Are there any specific step i missed? How do i remove '' from the list

Original Text file: https://www.youtube.com/channel/UCWTgK00SCKKNgpbsAgqzUxw/videos https://www.youtube.com/watch?v=4Dkl1K3mtHM

3 Answers 3

1

Files usually have a blank line at the end of them so you could manually remove the last item:

links = file.read().split("\n")[:-1]

the [:-1] means "everything up to and NOT including the last element".

Alternatively you can filter all blank lines (including in the middle) with:

links = [line for line in file.read().split("\n") if line and not line.isspace()]

We use list here because filter returns a generator. line and not line.isspace() means first that the line is not empty ('') and second that it doesn't consist only of space characters.

Sign up to request clarification or add additional context in comments.

Comments

1

In cases where the '' is not only at the end of the list, just iterate through the list while checking with a conditional while appending to a new list.

links = ['https://www.youtube.com/channel/UCWTgK00SCKKNgpbsAgqzUxw/videos','https://www.youtube.com/watch?v=4Dkl1K3mtHM', '']
new_links = []
for i in links:
    if i != '':
        new_links.append(i)
print(new_links)

This would return ['https://www.youtube.com/channel/UCWTgK00SCKKNgpbsAgqzUxw/videos', 'https://www.youtube.com/watch?v=4Dkl1K3mtHM']

Comments

0

You can also use strip for this

file = open("file path", "r")
links = file.read().strip().split("\n")
print(links)

strip() is an inbuilt function in Python programming language that returns a copy of the string with both leading and trailing characters removed (based on the string argument passed).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.