如何使用Python在文件中写入多行

2024-06-13 15:20:06 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我知道要写多少行,我知道如何将多行写入一个文件。但是,当我想写多行时,问题就来了,但是,我不知道它们会有多少

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

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

这给了我想要的输出。所以,我试图通过添加以下内容将内容写入文件:

^{pr2}$

但是,不幸的是,它只写第一个链接。如何添加其他链接?在


Tags: 文件incom应用程序httpfor网站链接
3条回答

下面的代码应该允许您向一个文件写入多行。在

 with open(fa, "w") as f:
    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:
            z = a['href']
            f.write('http://www.crunchyroll.com{}\n'.format(z) )

只需先打开文件然后在迭代时写入:

 with open(fa, "w") as f:
    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:
            z = a['href']
            f.write('http://www.crunchyroll.com{}\n'.format(z) )

除非您希望将所有链接放在一行中,否则在连接的链接末尾需要\n。你的代码也会写最后一个链接而不是第一个链接。在

输出:

^{pr2}$

确保将链接写入for循环中。使用with命令也可以节省手动关闭文件的时间。 这应该是有效的:

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)

相关问题 更多 >