回覆列表
  • 1 # 老生談笑

    with open("file.txt", "r") as old_file: with open("file.txt", "r+") as new_file: current_line = 0 # 定位到需要刪除的行 while current_line < (del_line - 1): old_file.readline() current_line += 1 # 當前游標在被刪除行的行首,記錄該位置 seek_point = old_file.tell() # 設定游標位置 new_file.seek(seek_point, 0) # 讀需要刪除的行,游標移到下一行行首 old_file.readline() # 被刪除行的下一行讀給 next_line next_line = old_file.readline() # 連續覆蓋剩餘行,後面所有行上移一行 while next_line: new_file.write(next_line) next_line = old_file.readline() # 寫完最後一行後截斷檔案,因為刪除操作,檔案整體少了一行,原檔案最後一行需要去掉 new_file.truncate()

  • 2 # 使用者7698895345900

    import os

    DELNUM=12

    i=1

    openFileHandle=open("filename","r")

    writeFileHandle=open("Temp","w")

    while 1:

    line=openFileHandle.readline()

    if line:

    if i

    i=i+1

    print "找到%d行:%s"%(DELNUM,line)

    continue

    else:

    i=i+1

    writeLine="%s\n"%line

    writeFileHandle.write(writeLine)

    else:

    print "匹配%d行失敗,檔案已到末尾"%DELNUM

    break

    openFileHandle.close()

    writeFileHandle.close()

    os.remove("filename")

    os.rename("Temp","filename")

    print "All Done!"

  • 中秋節和大豐收的關聯?
  • 英語口語發音技巧?