python - 打印变量并在循环中附加文件中的一行

标签 python

我已经研究过这个问题,但找不到确切的答案。我已经找到了当涉及 2 个列表时附加的答案,但这是不同的,所以这里是。

我正在创建一个非常基本的模糊器,但在将目录名称附加到地址末尾时遇到问题。这是我到目前为止所拥有的。

预期输出如下;

www.website.com/1
www.website.com/2
www.website.com/3
www.website.com/4

等等。但我得到了完全不同的东西。这是我测试的第一段代码。

>>> host = "www.website.com/"
>>> path = [line.strip() for line in open("C:/Users/Public/Documents/tester.txt", 'r')]
>>> print str(host) + str(path)

返回以下内容

www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

第二次尝试是这样的;

>>> host = "www.website.com/"
>>> path = [line.strip() for line in open("C:/Users/Public/Documents/tester.txt", 'r')]
>>> for line in path:
print str(host) + str(path)

返回了这个;

www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

我可以准确地看到发生了什么以及为什么会发生,但我不知道如何达到预期的输出。我还需要过滤掉我认为“打印”不会出现的特殊字符。当打印以列表形式读取某些内容时,可能有不同的打印规则。

我想过一些愚蠢的复杂方法,例如计算文件中的行数,然后使用该计数将其放入 while 循环中,但我确信有些东西我可以使用,或者我做错了。我的 Python 知识并不出色。

有人可以帮忙吗?

最佳答案

当使用 for 循环时,您已经快到了,连接列表中的元素(在您的情况下位于变量“line”中),而不是再次连接完整列表。

代码-

for line in path:
    print str(host) + str(line)

关于python - 打印变量并在循环中附加文件中的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32131730/

相关文章:

python - 如何在 TensorFlow v2.0 中正确应用梯度

python - 如何可靠地从 TCP 套接字中准确读取 n 个字节?

python - 访问https网页时获取urllib2权限被拒绝错误?

python - 具有不同偏移向量的 Pandas 向量化日期偏移操作

python - 根据条件从另一个数据框中添加列

python - 从嵌套字典中获取值

python - 有没有办法在一个命令中获取 python 中的中位数索引?

python - 在 python 中使用返回的变量

python - python ctypes中的未知数组长度

python - 谷歌应用引擎 : Determine whether Current Request is a Taskqueue