【问题标题】:Using loop to write in files使用循环写入文件
【发布时间】:2017-06-29 13:04:54
【问题描述】:

我正在尝试从我一直在看的所有教程中下载原始代码,所以我做了这个:

import requests
from urllib import request
from bs4 import BeautifulSoup

page_url='https://github.com/buckyroberts/Source-Code-from-
Tutorials/tree/master/Python'

def page(main_url):
    code=requests.get(main_url)
    text=code.text
    soup=BeautifulSoup(text, "html.parser")
    for link in soup.findAll('a', {'class': 'js-navigation-open'}):
        code_url='https://github.com'+link.get('href')
        codelist(code_url)

def codelist(sec_url):
    code = requests.get(sec_url)
    text = code.text
    soup = BeautifulSoup(text, "html.parser")
    for link in soup.findAll('a', {'id': 'raw-url'}):
        raw_url='https://github.com'+link.get('href')
        rawcode(raw_url)

def rawcode(third_url):
    response = request.urlopen(third_url)
    txt = response.read()
    lines = txt.split("\\n")
    dest_url = r'go.py'
    fx = open(dest_url, "w")
    for line in lines:
        fx.write(line + "\n")
    fx.close()

page(page_url)

当我运行此代码时,我希望从此处创建 40 个 py 文件,其中包含 40 个不同的代码-https://github.com/buckyroberts/Source-Code-from-Tutorials/tree/master/Python 但它不起作用。两次,它随机选择只下载 40 个文件中的一个。像这样-

在调用第三个函数之前,前两个函数可以很好地协同工作。但第三个单独工作正常。

我从 4 天前开始学习 Python,我们将不胜感激。谢谢各位!

【问题讨论】:

  • 您已覆盖您的文件,这会删除之前的文件及其内容。试试fx = open(dest_url, "a"),它将(a)添加代码而不是重新(w)编写它
  • 最好是保存在不同的文件中(你可以使用一个简单的计数器来完成,它会增加从而改变文件名)。所以你可以在之后运行它们
  • @Nuageux 谢谢你,先生。无法想象一封信就解决了它。但是,所有代码都下载到一个文件中。你会推荐什么循环它以创建 40 个不同的文件?再次感谢。
  • @Nuageux 将最后一个函数更改为这个,先生 - x=2 response = request.urlopen(third_url) txt = response.read() txt_str=str(txt) lines = txt_str.split("\\n") dest_url = str(x)+'.py' fx = open(dest_url, "a") for line in lines: fx.write(line + "\n") fx.close() x+=1 它创建了一个文件“2.py”并将所有内容保存在其中。我的代码错了吗?
  • 您在函数的开头定义了x=2,因此它始终等于 2。我将编辑我的答案,以便您可以复制/粘贴

标签: pycharm python-3.4


【解决方案1】:

[关注 cmets] 为了方便更改文件名,您可以添加一个全局变量(此处为 cp),如下所示:

def rawcode(third_url):
    global cp
    dest_url = r'go_%s.py' % cp
    cp += 1
    print(dest_url)

cp = 0
page(page_url)

文件名将是“go_X.py",其中 X 从 0 到文件数

编辑 使用您的代码:

def rawcode(third_url):
    response = request.urlopen(third_url)
    txt = response.read()
    lines = txt.split("\\n")
    global cp # We say that we will use cp the global variable and not local one
    dest_url = r'go_%s.py' % cp
    cp += 1 # We increment for further calls
    fx = open(dest_url, "w") # We can keep 'w' since we will generate new files at each call
    for line in lines:
        fx.write(line + "\n")
    fx.close()

cp = 0 # Initialisation
page(page_url)

【讨论】:

  • 谢谢您,先生。你让我今天一整天都感觉很好。 :)
  • 不客气。随时将您的问题标记为已回答
  • 不知道该怎么做,先生。我在这里很新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多