2

除了我想要的以外,我有下面的代码做所有事情:-)。目标很简单,我试图将文本添加到目录(和子目录)中每个文件顶部的 appendtext 变量,脚本运行良好,但文本没有被附加。我哪里错了?

import os
import sys
import fnmatch
temp_fname = "temp_file"

appendtext="""Test string
"""
if len(sys.argv) < 2:
    sys.exit('Usage: test.py <build directory>')

for path,dirs,files in os.walk(sys.argv[1]):
    for fname in files:
        for pat in ['*.*']:
            if fnmatch.fnmatch(fname,pat):
                fullname = os.path.join(path,fname)
                with open(fullname, "r") as in_file:
                    with open(temp_fname, "w") as out_file:
                        out_file.write(appendtext)
                        for line in in_file:
                            out_file.write(line)
                os.rename(temp_fname, fullname)
4

2 回答 2

2

如果您希望文件顶部的文本,您应该执行以下操作:

temp_fname = "temp_file"
# the next line doesn't work in Python 2.5, 2.6, or 3.0
with open(fullname, "r") as in_file, open(temp_fname, "w") as out_file:
    out_file.write(appendtext)
    for line in in_file:
        out_file.write(line)
os.rename(temp_fname, fullname)

这是为 Python 2.6 重写的上述代码:

temp_fname = "temp_file"
with open(temp_fname, "w") as out_file:
    with open(fullname, "r") as in_file:
        out_file.write(appendtext)
        for line in in_file:
            out_file.write(line)
os.rename(temp_fname, fullname)

我们可以做得比这好一点。这始终使用相同的临时文件名 ( "temp_file"),并且该文件将始终在单个目录中创建(运行时的默认目录)。我们真正想要的是一个具有唯一名称的临时文件,该文件创建在与我们将要编辑的文件完全相同的目录中。Python 为我们提供了一个方便的模块,称为tempfile创建临时文件。

默认情况下,你只是得到一个打开的文件句柄,你不知道文件名。但是我们需要知道文件名,以便在临时副本完全完成后,我们可以将其重命名为原始文件名。 tempfile提供NamedTemporaryFile这样的情况。

这是一个完整的程序:

import fnmatch
import os
import sys
import tempfile

headertext = "# header text\n\n"

def want_this_file(fname):
    for pat in ['*']:
        if fnmatch.fnmatch(fname, pat):
            return True
    return False

def prepend_file(fullname, path):
    # with statement means temp file is written and closed at end of with
    with tempfile.NamedTemporaryFile(dir=path, delete=False) as out_file:
        with open(fullname, "r") as in_file:
                out_file.write(headertext)
                for line in in_file:
                    out_file.write(line)
        # before temp file is closed, get its name
        temp_fname = out_file.name
    # rename temp file to fullname, clobbering original
    os.rename(temp_fname, fullname)


start_directory = sys.argv[1]

for dirpath, dirnames, filenames in os.walk(start_directory):
    for fname in filenames:
        if want_this_file(fname):
            fullname = os.path.join(dirpath, fname)
            prepend_file(fullname, dirpath)

此答案使用模式“编写临时文件,然后将临时文件重命名为原始名称”。这是你应该这样做的方式。它让代码编写新版本,并且只有在新版本完全且成功编写,才会执行单个操作将新文件重命名为旧文件名。因此,如果在尝试编写新版本时出现任何问题,原始文件将保持不变。这是解决问题的安全方法。

我们想在与原始文件相同的目录中创建临时文件,这样os.rename()操作将非常便宜。在 Linux 系统上,您的系统临时/tmp目录tempfile(如果临时文件在同一目录下,重命名操作总是非常快速和安全。

编辑:这是代码的改进版本。这会捕获错误,并在重新引发异常发出错误信号之前清理临时文件。此外,正如 JF Sebastian 指出的那样,文件应该以二进制模式打开;这是这样做的。

import fnmatch
import os
import shutil
import sys
import tempfile

file_patterns_to_match = ['*']

headertext = "# header text\n\n"
# make any newlines in headertext match the system line ending
headertext = headertext.replace('\n', os.linesep)

def want_this_file(fname):
    for pat in file_patterns_to_match:
        if fnmatch.fnmatch(fname, pat):
            return True
    return False

def prepend_file(fullname, path):
    # with statement means temp file is written and closed at end of with
    with tempfile.NamedTemporaryFile(dir=path, delete=False) as out_file:
        # get the name immediately
        temp_fname = out_file.name

        try:
            # use binary mode to avoid newline translations
            with open(fullname, "rb") as in_file:
                out_file.write(headertext)
                shutil.copyfileobj(in_file, out_file)
        except Exception:
            # on any error, clean up temp file and re-raise exception
            try:
                os.remove(temp_fname)
            except Exception:
                print("unable to clean up temp file: " + temp_fname)
                pass
            raise
    # rename temp file to fullname, clobbering original
    os.rename(temp_fname, fullname)


start_directory = sys.argv[1]

for dirpath, dirnames, filenames in os.walk(start_directory):
    for fname in filenames:
        if want_this_file(fname):
            fullname = os.path.join(dirpath, fname)
            prepend_file(fullname, dirpath)
于 2013-01-09T02:06:03.513 回答
0

我知道你的问题是关于你的 python 脚本的。但是您可以使用 perl 在 bash 中的单行中实现这一点。

sgeorge-mn:stack sgeorge$ cat file_0*
Hi - 1 
Hi - 2 
Hi - 3 
Hi - 4 
Hi - 5 

sgeorge-mn:stack sgeorge$ find . -type f
./file_01.txt
./file_02.txt
./file_03.txt
./file_04.txt
./file_05.txt

sgeorge-mn:stack sgeorge$ find . -type f -exec  perl -pi -e 'print "Please donot add any comments \nThis is a header file.\nJust a test.\n" if $. == 1' {} \;

sgeorge-mn:stack sgeorge$ cat file_0*
Please donot add any comments 
This is a header file.
Just a test.
Hi - 1 
Please donot add any comments 
This is a header file.
Just a test.
Hi - 2 
Please donot add any comments 
This is a header file.
Just a test.
Hi - 3 
Please donot add any comments 
This is a header file.
Just a test.
Hi - 4 
Please donot add any comments 
This is a header file.
Just a test.
Hi - 5 
于 2013-01-09T02:22:47.537 回答