所以试图完成一个非常简单的脚本,这给了我难以置信的困难。它应该遍历指定的目录并打开其中的所有文本文件,并将它们全部附加相同的指定字符串。
问题是它根本没有对文件做任何事情。使用 print 测试我的逻辑,我将第 10 行和第 11 行替换为print f
(写入和关闭函数),并获得以下输出:
<open file '/Users/russellculver/documents/testfolder/.DS_Store', mode 'a+' at
所以我认为它在 f 变量中存储了 write 函数的正确文件,但是我不熟悉 Mac 如何处理 DS_STORE 或它在临时位置跟踪中扮演的确切角色。
这是实际的脚本:
import os
x = raw_input("Enter the directory path here: ")
def rootdir(x):
for dirpaths, dirnames, files in os.walk(x):
for filename in files:
try:
with open(os.path.join(dirpaths, filename), 'a+') as f:
f.write('new string content')
f.close()
except:
print "Directory empty or unable to open file."
return x
rootdir(x)
以及执行后终端中的确切返回:
Enter the directory path here: /Users/russellculver/documents/testfolder
Exit status: 0
logout
[Process completed]
然而,没有写入提供目录中的 .txt 文件。