'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']
Solution 1:[1]
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]
Solution 2:[2]
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()
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Serge Ballesta |
| Solution 2 | FLAK-ZOSO |
| Solution 3 | buhtz |
