python读写文件,如何将内容添加在文件开头呢
omefile.txt已经有内容了试过:f.open("somefile.txt",'r+')f.seek(0)开始f.write(),因为是写入多行...
omefile.txt已经有内容了试过:f.open("somefile.txt",'r+')f.seek(0)开始f.write(),因为是写入多行数据,就会覆盖掉原有文件的一部分
展开
展开全部
# coding: utf8
import os
f = open('a.txt', 'r')
content = f.read() # 读取文件内容
f_new = open('b.txt', 'w')
f_new.write('look !') # 开头写入内容
f_new.write(content) # 写入原文件内容
f.close()
f_new.close()
os.remove('a.txt') # 移除老文件
os.rename('b.txt', 'a.txt') # 新文件命名为老文件名
·········································································
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
eek( offset[, whence]) Set the file's current position, like stdio's fseek(). The whence argument is optional and defaults to 0 (absolute file positioning); other values are 1 (seek relative to the current position) and 2 (seek relative to the file's end). There is no return value. Note that if the file is opened for appending (mode 'a' or 'a+'), any seek() operations will be undone at the next write. If the file is only opened for writing in append mode (mode 'a'), this method is essentially a no-op, but it remains useful for files opened in append mode with reading enabled (mode 'a+'). If the file is opened in text mode (mode 't'), only offsets returned by tell() are legal. Use of other offsets causes undefined behavior. Note that not all file objects are seekable. 查看原帖>>
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询