如何在文件顶部添加新的文本行? [英] How can I add a new line of text at top of a file?
问题描述
我正在开发一个简单的程序,它使得Python脚本可执行,而且我正在添加解释器路径(#!/ usr / bin / python )。我试图做到这一点,但不是添加一个新行,而是取代当前的和删除下一行的一部分。我做错了什么?
我把源代码上传到Ubuntu Pastebin: http://pastebin.ubuntu.com/1032683/ 错误的代码在第28行和第31行之间:
wfile = open(file,'r +')
if wfile.readline()!=#!/ usr / bin / python\\\
:
wfile.seek )
wfile.write(#!/ usr / bin / python\\\
)
在iPad 2上使用Python 2.7.2(适用于iOS的Python ),也可以在同一个iPad中使用2.5.1 (Cydia端口)进行测试。
你不能做你想做的事情。寻找一个文件的开始,写一个将从该位置覆盖,而不是追加。
在文件的中间(或开始处)添加一行的唯一方法是写出一个新文件,并将数据插入到您希望的位置。 / p>
I'm developing a simple program which makes a Python script executable, and I'm working in the part which adds the interpreter path (#! /usr/bin/python). I tried to do it, but instead of adding a new line, it replaces the current and removes part of the next line. What I'm doing wrong?
I uploaded the source code to Ubuntu Pastebin: http://pastebin.ubuntu.com/1032683/ The wrong code is between lines 28 and 31:
wfile = open(file, 'r+')
if wfile.readline() != "#! /usr/bin/python\n":
wfile.seek(0)
wfile.write("#! /usr/bin/python\n")
Using Python 2.7.2 with an iPad 2 (Python for iOS), also using 2.5.1 in the same iPad (Cydia port) for testing.
You can't do what you're trying to do. Seeking to the beginning of a file and doing a write will overwrite from that position, not append.
The only way to add a line in the middle (or beginning) of a file is to write out a new file with the data inserted where you want it to.
这篇关于如何在文件顶部添加新的文本行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!