2011-05-06 29 views
38

我可以做到這一點使用一個單獨的文件的開頭,但我怎麼添加一行到文件的開始?前面加上行到一個文件中

f=open('log.txt','a') 
f.seek(0) #get to the first position 
f.write("text") 
f.close() 

這從開始以來的文件中追加模式打開的文件的末尾寫入。

+19

這不是追加,這是_pre_掛起。 – 2011-05-06 16:57:08

+5

[Python f.write()在文件開頭的可能的重複?](http://stackoverflow.com/questions/2677617/python-f-write-at-beginning-of-file) – geoffspear 2011-05-06 17:04:00

回答

58

在模式'a''a+',任何寫操作是在文件的最後完成,即使在當write()功能被觸發文件的指針當前時刻是不是在文件的結尾:指針移動到任何寫作之前的文件結尾。你可以用兩種方式做你想做的事。

1路,可如果沒有問題,可用於將文件加載到內存:

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允許重寫一行代碼;爲了進行就地操作,必須移動以下行,但我不知道機制

+1

'打開(文件名,'r +')爲f:'會關閉文件? – 2014-09-15 17:52:24

+2

@TomBrito是的,新['with'聲明】(https://docs.python.org/2/reference/compound_stmts.html#the-with-statement)可以讓你避免常見的'try' /'except'/'最後'樣板代碼。它是在Python版本'2.5'中添加的。 – 2015-04-01 14:12:41

+0

第一種方法刪除第一行。 – SanketDG 2015-07-01 01:39:34

14

在我所熟悉的所有文件系統,你不能做到這一點的地方。您必須使用輔助文件(您可以重命名以獲取原始文件的名稱)。

4

無法使用任何內置函數執行此操作,因爲它效率非常低。每次在前面添加一行時,您都需要將文件的現有內容向下移動。

有一個Unix/Linux工具tail可以從文件末尾讀取。也許你可以在你的應用程序中找到它。

6

要將代碼放到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) 
2
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 
相關問題