怪异/新颖的Python行为。打印字符串会产生不同的输出以保存到文件

时间:2014-12-09 15:22:16

标签: python html file file-io pycharm

我有一些代码。它旨在迭代一个文件夹,找到两个点并删除这两个点之间的所有内容,例如,

<head>
   <title>This is bad HTML</title>
</head>
<body>
  <h1> Remove me</h1>
  <div class="title">
    <h1> This is the good data, keep me</h1>

    <p> Keep this text </p>

  </div>
  <div class="footer">
    <h1> Remove me, I am pointless</h1>
  </div>
</body>

应该去:

  <div class="title">
    <h1> This is the good data, keep me</h1>

    <p> Keep this text </p>

  </div>

如果你的两点是:

start=<div class="title">
end=<div class="footer">

奇特之处 - 当我调用Python函数print来实现这一点时,代码完美地运行并且符合预期。

当我保存到文件时,生成的.html仅包含startend元素。我尝试打印出变量的每个值和每个可能的输出。这一切在打印到控制台时都有意义,但在保存到文件时会混乱。

这里发生了什么?

以下是代码:

import os

dir = os.listdir("C:/Users/FOLDER")

files = []

for file in dir:
    if file[-5:] == '.html':
        files.insert(0, file)

for fileName in files:
    file = open("C:/Users/FOLDER/" + fileName)
    content = file.read()
    file.close()

    start = content.find('<div class="title">')
    end = content.find('<div class="footer">')

    print "Start => " + start.__str__() #This is -1 if nothing found
    print "End =>" + end.__str__()      #Same

    start = start if (start != -1) else 0 #Removing -1 if found
    end = end if (end != -1) else len(content) #Same

    print "Edited start => " + start.__str__() #Verifying -1 changed
    print "Edited end -> " + end.__str__()     #Same

    print "CONTENTS=========>>>>>>>>>>>>>" + content[start:end-1] #prints perfectly fine


    #newContent = content[start:end-1]


    file = open("C:/Users/FOLDER/" + fileName[0:-5] + "_mod" + ".html", 'w')
    file.write(content[start:end]) #Writes only the start and end nodes to file, example below
    file.close()

这将保存到我的html,附加_mod:

<div class="title">
<h1>Title</h1>
</div>
</div>
<div class="footer">

除此之外,尽管在标题和页脚div之间有大量文字 - 尽管它在控制台中正确打印!

我在这里忽略了什么吗?看起来像一个新奇的小虫!

0 个答案:

没有答案