如何使用Python在文件的第一行前插入新行?
下面是更多的细节:
1st line
2nd line
3rd line
4th line
...
现在我想在 1st line
之前插入一行新的内容,叫做 zero line
。文件的内容看起来是这样的:
zero line
1st line
2nd line
3rd line
4th line
...
我知道 sed
命令可以做到这一点,但我想知道怎么用 Python 来实现?谢谢!
5 个回答
4
这里有一个实现方法,解决了之前一些方法的不足之处:
- 在出错的情况下不会丢失数据——@kriegar的版本就会丢失数据。
- 支持空文件——
fileinput
版本不支持。 - 保留原始数据:不会搞乱文件末尾的空格——
fileinput
版本会搞乱。 - 并且不会像net4geeks.com的版本那样把整个文件读入内存。
它模仿了fileinput
的错误处理:
import os
def prepend(filename, data, bufsize=1<<15):
# backup the file
backupname = filename + os.extsep+'bak'
try: os.unlink(backupname) # remove previous backup if it exists
except OSError: pass
os.rename(filename, backupname)
# open input/output files, note: outputfile's permissions lost
with open(backupname) as inputfile, open(filename, 'w') as outputfile:
# prepend
outputfile.write(data)
# copy the rest
buf = inputfile.read(bufsize)
while buf:
outputfile.write(buf)
buf = inputfile.read(bufsize)
# remove backup on success
try: os.unlink(backupname)
except OSError: pass
prepend('file', '0 line\n')
如果有的话,你可以使用cat
工具来复制文件。这可能会更高效:
import os
from subprocess import PIPE, Popen
def prepend_cat(filename, data, bufsize=1<<15):
# backup the file
backupname = filename + os.extsep+'bak'
try: os.unlink(backupname)
except OSError: pass
os.rename(filename, backupname)
# $ echo $data | cat - $backupname > $filename
with open(filename, 'w') as outputfile: #note: outputfile's permissions lost
p = Popen(['cat', '-', backupname], stdin=PIPE, stdout=outputfile)
p.communicate(data)
# remove backup on success
if p.poll() == 0:
try: os.unlink(backupname)
except OSError: pass
prepend_cat('file', '0 line\n')
5
这可能会引起你的兴趣
http://net4geeks.com/index.php?option=com_content&task=view&id=53&Itemid=11
根据你的问题调整的步骤:
# read the current contents of the file
f = open('filename')
text = f.read()
f.close()
# open the file again for writing
f = open('filename', 'w')
f.write("zero line\n\n")
# write the original contents
f.write(text)
f.close()
打开文件,把里面的内容读到一个叫'text'的变量里。
关闭文件。
用'w'参数重新打开文件,这样就可以写入内容了。
在文件开头写入一些新内容。
把文件原来的内容再写回去。
关闭文件。
请查看链接中的警告。
补充说明:
但要注意,这样做并不是完全安全的。如果你的Python程序在第二次打开文件后崩溃,而在再次关闭之前,你可能会丢失数据。
7
你可以使用 fileinput
这个工具。
>>> import fileinput
>>> for linenum,line in enumerate( fileinput.FileInput("file",inplace=1) ):
... if linenum==0 :
... print "new line"
... print line.rstrip()
... else:
... print line.rstrip()
...