很抱歉回答这个非常基本的问题。我是 Python 新手,正在尝试编写一个可以打印 URL 链接的脚本。 IP 地址存储在名为 list.txt 的文件中。我应该如何使用链接中的变量?能否请你帮忙?
# cat list.txt
192.168.0.1
192.168.0.2
192.168.0.9
script:
import sys
import os
file = open('/home/list.txt', 'r')
for line in file.readlines():
source = line.strip('\n')
print source
link = "https://(source)/result”
print link
output:
192.168.0.1
192.168.0.2
192.168.0.9
https://(source)/result
预期输出:
192.168.0.1
192.168.0.2
192.168.0.9
https://192.168.0.1/result
https://192.168.0.2/result
https://192.168.0.9/result
您需要传递实际变量,您可以迭代文件对象,这样您就不需要使用 readlines 并使用with
打开您的文件,因为它会自动关闭它们。如果您想查看每一行,您还需要在循环内打印str.rstrip()
将从每行末尾删除所有换行符:
with open('/home/list.txt') as f:
for ip in f:
print "https://{0}/result".format(ip.rstrip())
如果您想存储所有链接,请使用列表理解 http://www.python-course.eu/list_comprehension.php:
with open('/home/list.txt' as f:
links = ["https://{0}/result".format(ip.rstrip()) for line in f]
对于 python 2.6 你必须通过位置参数的数字索引, i.e {0}
using 字符串格式 https://docs.python.org/2/library/stdtypes.html#str.format .
您还可以使用名称传递给 str.format:
with open('/home/list.txt') as f:
for ip in f:
print "https://{ip}/result".format(ip=ip.rstrip())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)