【发布时间】: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