如何使用python在文件的第一行之前插入新行?

2024-03-29 02:36:13 发布

您现在位置: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呢?谢谢


Tags: 文件命令linesedzero
3条回答

下面是一个实现,它修复了sofar提出的其他方法中的一些缺陷:

它模拟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')

您可以使用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()
...

这可能很有趣

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()
  • 打开文件并读取 将内容转换为“文本”。

  • 关闭文件

  • 重新打开参数为“w”的文件 写入

  • 在文件前面写入文本

  • 写出 文件到文件

  • 关闭文件

阅读链接中的警告。

编辑:

But note that this isn't entirely safe, if your Python session crashes after opening the file the second time and before closing it again, you will lose data.

相关问题 更多 >