python - 输出到文件时遇到问题

标签 python

我这里有这个简单的代码

import os

path = (raw_input("Enter dir: "))   
f = open('script_list.log', 'w')
for dirpath, dirname, filenames in os.walk(path):
  for filename in [f for f in filenames]:
    f.write(str(filename) + "\n")
    print os.path.join(dirpath, filename)

当我运行它时,我得到以下信息

Enter dir: scripts
Traceback (most recent call last):
  File "C:\Documents and Settings\CRichards\My Documents\My Dropbox\this_code.py", line 8, in <module>
    f.write(str(filename) + "\n")
AttributeError: 'str' object has no attribute 'write'

我知道这一定很简单,只是我看不出来。

最佳答案

当您执行 [f for f in filenames] 时,您正在循环中重新绑定(bind) f。当您到达调用 f.write 的位置时,ffilenames 的最后一个成员,因此它是一个字符串。将外部 f 重命名为 logoutput 之类的名称,或者更好的是,摆脱无用的列表理解:

for file name in filenames:

足够了。

(列表理解不会引入新的作用域。)

关于python - 输出到文件时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9293530/

相关文章:

python - 向 Django 数据库添加元素

python - 将远程服务器连接到 spyder 以运行 Python 代码

python - python奇数或偶数函数的问题。返回 True 不起作用

python - mount 返回非零退出代码 64

python - Timsort 的合并模式

python - 使用 panda.read_csv 与 numpy.loadtxt 时的输出差异

python - 当 Pyro4 客户端意外断开连接时释放资源

python - 计算多个 pandas 数据帧中某个 pandas 行的特定列值低于另一个特定 pandas 行的次数

python - 使用 flask 进行 Bootstrap 选择

python - 函数的条形图 - 有条件地更改函数内条形的顺序