# 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.
下面是一个实现,它修复了sofar提出的其他方法中的一些缺陷:
它模拟
fileinput
的错误处理:如果可以使用
cat
实用程序复制文件,则可以使用该实用程序。可能更有效:您可以使用
fileinput
这可能很有趣
http://net4geeks.com/index.php?option=com_content&task=view&id=53&Itemid=11
适应你的问题:
打开文件并读取 将内容转换为“文本”。
关闭文件
重新打开参数为“w”的文件 写入
在文件前面写入文本
写出 文件到文件
关闭文件
阅读链接中的警告。
编辑:
相关问题 更多 >
编程相关推荐