脚本无法同时打开和附加多个文件

Script failing to open and append multiple files simultaneously

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

问题是它根本没有对文件做任何事情。使用 print 来测试我的逻辑,我将第 10 行和第 11 行替换为 print f(写入和关闭函数),并获得以下输出:

<open file '/Users/russellculver/documents/testfolder/.DS_Store', mode 'a+' at

所以我 认为 它将正确的文件存储在写入函数的 f 变量中,但是我不熟悉 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)

执行后终端中的确切 return:

Enter the directory path here: /Users/russellculver/documents/testfolder
Exit status: 0
logout

[Process completed]

但没有任何内容写入所提供目录中的 .txt 文件。

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

问题中的缩进方式,您 return 在编写第一个文件后立即从函数中退出;任何一个 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 错误;任何其他异常(尽管不太可能)都不会被捕获,因为它们可能与 non-existing/unwritable 文件无关。 )