0

所以试图完成一个非常简单的脚本,这给了我难以置信的困难。它应该遍历指定的目录并打开其中的所有文本文件,并将它们全部附加相同的指定字符串。

问题是它根本没有对文件做任何事情。使用 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 文件。

4

2 回答 2

1

问题中的缩进方式是在编写第一个文件后立即从函数返回;任何一个 for 循环都不会完成。从您只打印一个输出文件这一事实可以很容易地推测出这一点。

由于您没有对 rootdir 函数的结果做任何事情,我将完全删除 return 语句。

顺便说一句:使用 with 语句打开文件时无需使用 f.close() :它将自动关闭(即使出现异常)。这实际上就是引入 with 语句的目的(如有必要,请参阅上下文管理器的 pep)。

为了完整起见,这是我(大致)编写的函数:

def rootdir(x):
    for dirpaths, dirnames, files in os.walk(x):
        for filename in files:
            path = os.path.join(dirpaths, filename)
            try:
                with open(path, 'a+') as f:
                    f.write('new string content')
            except (IOError, OSError) as exc:
                print "Directory empty or unable to open file:", path

(请注意,我只捕获相关的 I/O 错误;不会捕获任何其他异常(尽管不太可能),因为它们可能与不存在/不可写的文件无关。)

于 2015-06-28T04:59:12.350 回答
0

Return 缩进错误,在一个循环后结束迭代。甚至没有必要,因此被完全删除。

于 2015-06-28T04:11:33.680 回答