如果您希望文件顶部的文本,您应该执行以下操作:
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)