【问题标题】:Python writing to a new file each new loopPython在每个新循环中写入一个新文件
【发布时间】:2015-06-23 20:03:43
【问题描述】:

我正在尝试使用 while 循环写入一系列新文件。循环的每次迭代都应该写入一个新文件,并在下一个循环开始之前关闭它。我正在使用 Python 2.7,如果可能的话,我想在不安装任何其他库的情况下解决这个问题。

我已经让程序可以写入单个文件,但是一旦我尝试使用循环,程序就会无限循环,一遍又一遍地写入初始文件。它没有关闭第一个文件并移动到下一个循环。代码如下:

更新:问题已解决。我将 while 循环中的所有内容移至一个单独的函数,并在 while 循环中重复调用它,同时增加参数的章节值。还要确保在箭头括号中考虑小写 p 以及大写 P。感谢大家的帮助!

import urllib

storyID = raw_input("Please Enter Story ID: ")
chapters = raw_input("Please Enter the number of Chapters: ")
countDown = int(chapters)
countUp = 1

while countUp <= countDown :

    storyURL = "https:website/" + storyID + "/" + str(countUp) + "/"
    f = urllib.urlopen(storyURL)

    with open ('chapter' + str(countUp) + '.html', 'a') as g:

        bof = False
        eof = False


        while eof == False :
            line = f.readline()
            if "<P>" in line and bof == False :
                bof = True
                g.write("""<html>\n<meta charset='utf-8'>\n
                <META NAME='ROBOTS' CONTENT='NOARCHIVE'>\n
                <META http-equiv='X-UA-Compatible' content='IE=edge'>\n
                <META NAME='format-detection' content='telephone=no'>\n
                <META NAME='viewport' content='width=device-width'>\n
                <meta name="google-translate-customization" content="6babbc5ad0624c76-e1cef323edf23c09-g0466c4b8ae39c7a2-12">\n""")
                g.write(line)

            elif "Chapter Navigation" in line and bof == True:
                eof = True
                g.write ("</html>")

            elif bof == True :
                g.write(line)
    g.close()
    countUp = countUp + 1

【问题讨论】:

    标签: python-2.7


    【解决方案1】:
    TRY THIS WAY....when you fetch the url use read() method first
    ################
    import urllib
    
    storyID = raw_input("Please Enter Story ID: ")
    chapters = raw_input("Please Enter the number of Chapters: ")
    countDown = int(chapters)
    countUp = 1
    
    while countUp <= countDown :
    
        storyURL = "https:website/" + storyID + "/" + str(countUp) + "/"
        f = urllib.urlopen(storyURL)
        data = f.read()
    
        with open ('chapter' + str(countUp) + '.html', 'w') as g:
              g.write(data)
    
        countUP = countUp + 1
    

    【讨论】:

    • 我试图运行它,但是得到了以下错误 Traceback (last recent call last): File "fetch2.py", line 14, in g.write(f) TypeError: expected a字符缓冲区对象
    • 错过一步:打开url后使用read()方法保存数据。使用保存的数据并写入文件。
    【解决方案2】:

    案件很重要。

    countUp = countUp + 1
    

    更好:

    countUp += 1
    

    【讨论】:

    • 这样就解决了它永远不会超过最外层 while 循环的第一次迭代的问题。我犯了愚蠢的错误。但现在我遇到了第二个循环的问题。它创建了第二个文件,但没有向其中写入任何内容,并且似乎无限循环,因为我必须强制它结束。我打开、写入和关闭文件的方式有问题吗?
    猜你喜欢
    • 2022-06-15
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    • 2015-06-29
    • 2019-12-15
    • 2022-07-01
    相关资源
    最近更新 更多