[英]Python: file write and iterating re.sub from dict only writes last occurrence
[英]Python trying to write. But only writes last value and not all of them
我正在使用硒抓取网页。 从那个网页上,有多个 div 与我放在列表中的同一个类。 然后尝试从中获取一些信息。 这将返回以下内容; a\\nb\\nc\\nd\\n
(只是abcd
但在其他行)。 然后几次。 所以我得到以下列表; ['a\\nb\\nc\\nd\\n', 'e\\nf\\ng\\nh\\n']
等等。我已经拆分了这些值,生成的是 json 字符串。 所以返回一个字符串; ['["a", "b", "c", "d"]', '["e", "f", "g", "h"]']
这在我的打印时一切正常安慰。 但现在我希望它把每个项目都放在列表中,所以每个 json. 到一个新行的文本文件中。 所以我尝试了这个;
for snipe in snipes:
with open('snipes.txt', 'w') as f:
snipe = json.dumps(s, separators=(',',':'))
print snipe
f.write(snipe+"\n")
f.close()
所以打印snipe
工作一切正常,它打印了所有的值。 但是当我检查snipes.txt
它只有列表中的最后一个值。 并非所有这些都在所有单独的线路上。
我怎样才能解决这个问题?
主要问题是您正在打开文件、写入一行、关闭它、下一个循环、通过再次写入来覆盖文件等。请考虑以下事项:
# always open the file before looping to keep it open
# using with will auto close the file when done
with open('snipes.txt', 'w') as f:
# loop through and write everything
for snipe in snipes:
snipe = json.dumps(s, separators=(',',':'))
print snipe
f.write(snipe+"\n")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.