无法写入 Python 的文件

fail to write to file with Python

我写了一些 python 代码来从网上提取 table 并将其保存到文件中。在交互模式下,我能够测试我的代码并将数据保存到文件中。然而,当我 运行 带有命令行的文件时,它没有给出安迪错误信息,但文件是空的。

这是我的代码的一部分。我运行2.7.9下windows

    rows=soup.tbody.findAll('tr')
outf=open('.\data\dec','w')
for tr in rows:
    cols=tr.findAll('td')
    out='*'.join([c.text.encode('utf-8') for c in cols])
    outf.write(out+'\n')

    outf.close
    browser.close()

不确定缩进,这看起来很奇怪。请尝试

outf.close()

因为你想调用方法,而不是引用内存中的方法。

我认为您的问题来自您的:

  1. 关闭 for 循环中的 outf;
  2. 滥用.close()(你只有.close);和
  3. 在您的 for 循环中关闭 browser

您的代码已发布将只处理一行,然后关闭您的文件和浏览器!

如果像这样重写,您可能会发现您的代码可以正常工作:

rows=soup.tbody.findAll('tr')

with open('.\data\dec','w') as file_handle:
    for row in rows:
        cols = tr.findAll('td')
        file_handle.write('*'.join([c.text.encode('utf-8') for c in cols])+'\n')
browser.close()

注意: 使用 with 会自动为您关闭文件 ;)

我会使用如下内容:

rows = soup.tbody.findAll('tr')
with open('.\data\dec', 'w') as file:
    for tr in rows:
    cols = tr.findAll('td')
    out = '*'.join([c.text.encode('utf-8') for c in cols])
    file.write('%s\n' % out)

browser.close()