如何使用python在文件中写多行 [英] how to write multiple lines in a file using python

查看:350
本文介绍了如何使用python在文件中写多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何将多行写入文件,如果我知道要写多少行。但是,问题出现的时候我想写多行,但是,我不知道它们会有多少

i know how to write multiple lines to a file, if I know how many I want to write. But, the problem comes when I want to write multiple lines, but, I don't know how much they will be

我正在开发一个应用程序网站并将结果的链接存储在文本文件中。但是,我们不知道它会回复多少行。我的代码现在如下。

I am working on an app which scraps from a website and stores the links of the result in a text file. But, we don't know how many lines will it reply with. My code is as follows right now.

r = requests.get('http://www.crunchyroll.com/i-cant-understand-what-my-husband-is-saying')
soup = BeautifulSoup(r.text)
print soup.title
subtitles = soup.findAll('div',{'class':'wrapper container-shadow hover-classes'})
for episode in subtitles:
  x = episode.find_all('a')
  for a in x:
   #print a['href']

   z = a['href']

  l = 'http://www.crunchyroll.com'+ z
  print l

这给了我想要的输出。所以,我尝试通过添加以下内容在文件中写东西:

This gives me the desired output.So,I tried to write stuff up in a file by adding :

file = open("BatchLinks.txt", "w")
file.write(l)
file.close()

但不幸的是,它只写了第一个链接。我怎样才能添加其他链接?

But, unfortunately, it only writes the first link. How can I add other links too?

推荐答案

确保在for循环内写入链接。使用命令保存以便手动关闭文件。
这应该有效:

Make sure to write the link inside the for loop. Using a with command save you for manually closing the file as well. This should work:

r = requests.get('http://www.crunchyroll.com/i-cant-understand-what-my-husband-is-saying')
soup = BeautifulSoup(r.text)
print soup.title
subtitles = soup.findAll('div',{'class':'wrapper container-shadow hover-classes'})

with open("BatchLinks.txt","w") as file: 

    for episode in subtitles:
        x = episode.find_all('a')
        for a in x:

            z = a['href']

            link = 'http://www.crunchyroll.com'+ z
            print link
            file.write(link)

这篇关于如何使用python在文件中写多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆