加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python-2.7 – 在python中将多行写入文件的问题

发布时间:2020-12-20 12:01:17 所属栏目:Python 来源:网络整理
导读:我想将多个特定链接(图像的网址)下载到txt文件(或任何文件中,其中所有链接可以列在彼此之下). 我得到了它们,但是代码在另一个顶部的每个链接上都存在,最后它只保留一个链接:(.我也不想重复网址 def dlink(self,image_url): r = self.session.get(image_url,s
我想将多个特定链接(图像的网址)下载到txt文件(或任何文件中,其中所有链接可以列在彼此之下).

我得到了它们,但是代码在另一个顶部的每个链接上都存在,最后它只保留一个链接:(.我也不想重复网址

def dlink(self,image_url):
        r = self.session.get(image_url,stream=True)
        with open('Output.txt','w') as f:
            f.write(image_url + 'n')

解决方法

Edit

我的错误,因为它是一种方法,你会多次调用它,如果你以写模式(‘w’)或类似方式打开它,如果文件存在,它将覆盖现有文件.
?所以,如果你使用’a’方式,你可以看到:

Opens a file for appending. The file pointer is at the end of the file
if the file exists. That is,the file is in the append mode. If the
file does not exist,it creates a new file for writing.

image_url中的另一个基本问题是列表,因此您需要逐行编写它:

def dlink(self,'a') as f:
            for url in list(set(image_url)):
                f.write(image_url + 'n')

另一种方法:

your_file = open('Output.txt','a')
r = self.session.get(image_url,stream=True)
for url in list(set(image_url)):
  your_file.write("%sn" % url)
your_file.close() #dont forget close it :)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读