我可以使用单独的文件来执行此操作,但是如何在文件的开头添加一行?
f=open('log.txt','a')
f.seek(0) #get to the first position
f.write("text")
f.close()
由于文件是在追加模式下打开的,因此此操作从文件末尾开始写入。
我可以使用单独的文件来执行此操作,但是如何在文件的开头添加一行?
f=open('log.txt','a')
f.seek(0) #get to the first position
f.write("text")
f.close()
由于文件是在追加模式下打开的,因此此操作从文件末尾开始写入。
Answers:
在模式'a'或中'a+',即使在write()触发函数的当前时刻,文件的指针也不位于文件的末尾,任何写入都在文件的末尾进行:在进行任何写入之前,指针已移至文件的末尾。您可以通过两种方式完成您想要的事情。
第一种方式,如果没有问题可以将文件加载到内存中,则可以使用:
def line_prepender(filename, line):
with open(filename, 'r+') as f:
content = f.read()
f.seek(0, 0)
f.write(line.rstrip('\r\n') + '\n' + content)
第二种方式:
def line_pre_adder(filename, line_to_prepend):
f = fileinput.input(filename, inplace=1)
for xline in f:
if f.isfirstline():
print line_to_prepend.rstrip('\r\n') + '\n' + xline,
else:
print xline,
我不知道这种方法如何在后台运行,以及是否可以在大文件中使用。传递给输入的参数1允许在适当位置重写一行;为了进行就地操作,必须向前或向后移动以下几行,但是我不知道该机制
with open(filename,'r+') as f:将关闭文件?
为了使代码成为NPE的答案,我认为最有效的方法是:
def insert(originalfile,string):
with open(originalfile,'r') as f:
with open('newfile.txt','w') as f2:
f2.write(string)
f2.write(f.read())
os.rename('newfile.txt',originalfile)
num = [1, 2, 3] #List containing Integers
with open("ex3.txt", 'r+') as file:
readcontent = file.read() # store the read value of exe.txt into
# readcontent
file.seek(0, 0) #Takes the cursor to top line
for i in num: # writing content of list One by One.
file.write(str(i) + "\n") #convert int to str since write() deals
# with str
file.write(readcontent) #after content of string are written, I return
#back content that were in the file
如果您不介意再次写入文件,执行此操作的明确方法如下
with open("a.txt", 'r+') as fp:
lines = fp.readlines() # lines is list of line, each element '...\n'
lines.insert(0, one_line) # you can use any index if you know the line index
fp.seek(0) # file pointer locates at the beginning to write the whole file again
fp.writelines(lines) # write whole lists again to the same file
请注意,这不是就地替换。它正在再次写入文件。
总而言之,您将读取一个文件并将其保存到列表中,然后修改该列表,然后将该列表再次写入具有相同文件名的新文件中。