我尝试使用while循环写入一系列新文件。循环的每次迭代都应该写入一个新文件,并在下一个循环开始之前关闭它。我使用的是Python 2.7,我想解决这个问题而不必在可能的情况下安装任何其他库。
我已经让程序用于写入单个文件,但是一旦我尝试使用循环,程序就会无限循环,一遍又一遍地写入初始文件。它不会关闭第一个文件并转移到下一个循环。这是代码:
更新:问题已解决。我将while循环中的所有内容移动到一个单独的函数中,并在while循环中重复调用它,同时递增参数的chapter值。还要确保在箭头括号和大写字母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
答案 0 :(得分:0)
案件很重要。
countUp = countUp + 1
更好的是:
countUp += 1
答案 1 :(得分:0)
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