麻烦输出到文件

gee*_*ers 1 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)
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我得到以下内容

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'
Run Code Online (Sandbox Code Playgroud)

我知道它必须是简单的东西,我只是看不到它.

Fre*_*Foo 5

f当你这样做时,你会在循环中重新绑定[f for f in filenames].当你到达f.write被调用的点时,f是最后一个成员filenames,所以它是一个字符串.将外部重命名为f类似logoutput更好的东西,摆脱无用的列表理解:

for file name in filenames:
Run Code Online (Sandbox Code Playgroud)

就足够了.

(列表推导不会引入新的范围.)