从txt文件列表中读取链接 - Python

时间:2017-06-02 10:45:12

标签: python python-3.x

我有一个名为links.txt的文件,其中包含以下列表 (列表名称:Set_of_links):

[https://link1.comhttps://link2.comhttps://link3.com/hellohttps://links4.com/index.php ,. 。 。 。 ]

我正在执行程序,links_python.py需要从该文件中读取每个链接并将其存储在python脚本中的本地变量中。我使用以下程序:

i = 0
with open(links.txt, "r") as f:
    f.read(set_of_links[i])
    i+=1

似乎无法正常工作。

3 个答案:

答案 0 :(得分:1)

如果您只有一行链接,请丢弃括号和空格并尝试

links = []
with open('links.txt')) as f:
    links = f.read().split(',')

答案 1 :(得分:0)

请尝试以下操作:感谢@Jean进行编辑

i = 0
with open(links.txt, "r") as f:
    set_of_links[i] = f.readline()
    i+=1

答案 2 :(得分:0)

如果您要将每个链接分开并将其附加到set_of_links,则可以使用re替换这些字符[],,然后通过拆分创建列表。使用列表推导它应该看起来像:

import re
with open('links.txt', 'r') as f:
    set_of_links = [re.sub(r'[(\[\],)]', '', x) for x in f.read().split()]
    print set_of_links

输出:

['https://link1.com', 'https://link2.com', 'https://link3.com/hello', 'https://links4.com/index.php']
相关问题