Pycharm 使用循环写入文件

Pycharm 使用循环写入文件,pycharm,python-3.4,Pycharm,Python 3.4,我正试图从我一直在观看的所有教程中下载原始代码,因此我制作了以下内容: 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_ur

我正试图从我一直在观看的所有教程中下载原始代码,因此我制作了以下内容:

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个不同的代码组成- 但它不起作用。它两次随机选择下载40个文件中的一个。像这样-

在调用第三个函数之前,前两个函数可以很好地协同工作。但仅第三种方法就行了


4天前我开始学习Python,任何帮助都将不胜感激。谢谢大家

[以下注释]为了方便更改文件名,您可以添加一个全局变量(此处为
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)

您的文件被覆盖,删除了以前的文件及其内容。尝试
fx=open(dest_url,“a”)
,这将(a)添加代码,而不是重新编写。最好是保存在不同的文件中(您可以使用一个简单的计数器,它将递增,从而更改文件名)。这样你就可以运行它们了after@Nuageux谢谢你,先生。无法想象一封信就能解决它。但是,所有的代码都是在一个文件中下载的。您建议如何循环以创建40个不同的文件?再次感谢。@Nuageux将最后一个函数更改为sir-
x=2 response=request.urlopen(third\u url)txt=response.read()txt\u str=str(txt)lines=txt\u str.split(“\\n”)dest\u url=str(x)+'.py'fx=open(dest\u url,“a”),用于以下行:fx.write(line+“\n”)fx.close()x+=1
它创建了一个文件“2.py”,并保存了其中的所有内容。我的代码错了吗?您在函数的开头定义了
x=2
,因此它总是等于2。我会修改我的答案,这样你就可以抄了谢谢你,先生。你让我开心不客气。请随便回答我的问题,我不知道该怎么做,先生。我是新来的。