要避免通过调用函数向文件开头添加文本,您可以使用以下代码示例中的解决方法:
def append_to_file(filename, text):
with open(filename, 'r+') as file:
content = file.read()
file.seek(0, 0)
file.write(text + '\n' + content)
# 示例用法
filename = 'example.txt'
text_to_add = 'This is the new text'
append_to_file(filename, text_to_add)
上述代码中的append_to_file
函数接受一个文件名和要添加的文本作为参数。它首先打开文件并将其内容读入一个变量。然后,使用seek
函数将文件指针移动到文件开头,并使用write
函数将新文本和原始内容写入文件。这样就可以在文件开头添加文本,而不会覆盖原有的内容。
请注意,此方法仅适用于文本文件。如果您要向二进制文件添加文本,您需要使用其他方法。