chauhany
chauhany

Reputation: 79

Creating a list from a text file

I have a text file called my_urls.txt that has 3 URLs:

example1.com
example2.com
example3.com
with open("../test_data/my_urls.txt", "r") as urlFile:
    urls_list = urlFile.readline().split('\n')
    print(urls_list)


['example1.com', '']

I wonder why urls_list is not giving me ['example1.com', 'example2.com', 'example3.com']

Upvotes: 1

Views: 364

Answers (4)

Serge Ballesta
Serge Ballesta

Reputation: 148900

readline reads a single line so it cannot give you anything past the first line. read could read the whole file and you will then be able to split the result on newlines.

But IMHO, as a file object is an iterable of lines, the Pythonic way would be to use a comprehension:

with open("../test_data/my_urls.txt", "r") as urlFile:
    urls_list = [line.rstrip() for line in urlFile]

Upvotes: 3

FLAK-ZOSO
FLAK-ZOSO

Reputation: 4098

with open("../test_data/my_urls.txt", "r") as urlFile:
    urls_list = urlFile.readline().split('\n')

Nice try I would say, since you are using readline() to read the content of the file, but you are only reading one line.


If you want to read the whole file and then .split() it in lines, you just have to do this:

with open("../test_data/my_urls.txt", "r") as urlFile:
    urls_list = urlFile.read().split('\n')

You can get the list of the lines in an other way:

urls_list = urlFile.readlines()

Upvotes: 1

quamrana
quamrana

Reputation: 39354

You need to iterate over the open file. This iterates over the lines for you:

with open("../test_data/my_urls.txt", "r") as urlFile:
    urls_list = []
    for url in urlFile:
        urls_list.append(url.strip())
    print(urls_list)

Upvotes: 0

buhtz
buhtz

Reputation: 12162

Because you do readline() instead of read(). In your example you only read the first line of the file and then close it.

Try this

urls_list = urlFile.read().split('\n')

It will read the whole file content at once.

Upvotes: 0

Related Questions