python读写文件,如何将内容添加在文件开头呢

2025-04-14 16:38:25
推荐回答(3个)
回答1:

fp.seek(offset[,whence])
#将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的,一般为正数。但如果提供了whence参数就不一定了,whence可以为0表示从头开始计算,1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。需要注意,如果文件以a或a+的模式打开,每次进行写操作时,文件操作标记会自动返回到文件末尾。

回答2:


# 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') # 新文件命名为老文件名


·········································································

回答3:

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. 查看原帖>>