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

Jas*_*son 2 python file-io file

更多细节如下:

1st line

2nd line

3rd line

4th line

...
Run Code Online (Sandbox Code Playgroud)

现在想插入一个zero line之前命名的新行1st line.文件如下所示:

zero line

1st line

2nd line

3rd line

4th line

...
Run Code Online (Sandbox Code Playgroud)

我知道sed命令可以做这项工作,但如何使用python做到这一点?谢谢

kur*_*umi 6

您可以使用 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()
...
Run Code Online (Sandbox Code Playgroud)


DTi*_*ing 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()
Run Code Online (Sandbox Code Playgroud)
  • 打开文件并将内容读入“文本”。

  • 关闭文件

  • 使用参数“w”重新打开文件进行写入

  • 写入要添加到文件前面的文本

  • 将文件原来的内容写入文件

  • 关闭文件

阅读链接中的警告。

编辑:

但请注意,这并不完全安全,如果您的 Python 会话在第二次打开文件后和再次关闭文件之前崩溃,您将丢失数据。