質問

どのように一つを削除しても最終ラインのファイルとpython?

入力ファイルの例:

hello
world
foo
bar

出力ファイルの例:

hello
world
foo

私は、次のコードの行数のファイルがわからないのできれいに表示されない特定の行番号です。私は新しいpythonい場合があり方を教えてください.

    try:
        file = open("file")
    except IOError:
        print "Failed to read file."
    countLines = len(file.readlines())

編集:

きっかけになるかもしれないとで様々な答え:主にいちごのものは私のせいにしている。

#!/usr/bin/env python

import os, sys

readFile = open("file")

lines = readFile.readlines()

readFile.close()
w = open("file",'w')

w.writelines([item for item in lines[:-1]])

w.close()
役に立ちましたか?

解決

また、上記のコードとその後:-

lines = file.readlines()
lines = lines[:-1]

このことを知ることができるた配列のラインを含むすべてのラインが立つブログが数多くあります。

他のヒント

私は日常的に多く-ギガバイトのファイル、ループを指摘したように、このよう答えが動作しなかった。の溶液を使ってい:

with open(sys.argv[1], "r+", encoding = "utf-8") as file:

    # Move the pointer (similar to a cursor in a text editor) to the end of the file
    file.seek(0, os.SEEK_END)

    # This code means the following code skips the very last character in the file -
    # i.e. in the case the last line is null we delete the last line
    # and the penultimate one
    pos = file.tell() - 1

    # Read each character in the file one at a time from the penultimate
    # character going backwards, searching for a newline character
    # If we find a new line, exit the search
    while pos > 0 and file.read(1) != "\n":
        pos -= 1
        file.seek(pos, os.SEEK_SET)

    # So long as we're not at the start of the file, delete all the characters ahead
    # of this position
    if pos > 0:
        file.seek(pos, os.SEEK_SET)
        file.truncate()

これは当てはまりませんpythonを使うだが、pythonの間違ったツールはこのタスクをしています。利用できる標準の*nix明 head, を実行し

head -n-1 filename > newfile

るすべてコピーしますが、最後のファイル名をnewfile.

想いのこのPythonことになるするのに十分な大きなファイルリストスライスなのに十分なまでの単一パスにファイル:

last_line = None
for line in file:
    if last_line:
        print last_line # or write to a file, call a function, etc.
    last_line = line

ないの優雅なコードが世界の中での作成"にチェックを入れます。

基本的にバッファーラインごとにファイルのlast_line変数の繰り返し処理毎に出力する以前の繰り返します。

システム ファイルです。truncate() 作品は、なにができるようなこと:

file = open('file.txt', 'rb')
pos = next = 0
for line in file:
  pos = next # position of beginning of this line
  next += len(line) # compute position of beginning of next line
file = open('file.txt', 'ab')
file.truncate(pos)

自分の試験-ファイルです。tell()ない場合、読み込みを行線、想定外のショックが発生する蓋然によるバッファリングは混乱します。だからこの追加の長さの線に出ます。この作品システムの行区切り文字で終わる' '.

こちらは自溶液のためのlinuxユーザー:

import os 
file_path = 'test.txt'
os.system('sed -i "$ d" {0}'.format(file_path))

なを読み込む必要があり、繰り返し処理を実行してファイルがエラーになります。

刺激にならないpropoundす:

with open('file_name', 'r+') as f:
  f.seek(0, os.SEEK_END) 
  while f.tell() and f.read(1) != '\n':
    f.seek(-2, os.SEEK_CUR)
  f.truncate()

したが試していないでください、嫌いなが)いにある、高速のものです。そのCの溶液が、なかなか可能です。なPythonicます。この理論から言うまでもない。

最初に把握しておく必要があり、エンコードのファイルです。設定変数のバイト数の文字をエンコードの使用(1バイトASCII). CHARsize (ません).からす1バイトASCIIファイルです。

その後ブファイルのサイズを設定 FILEsize いています。

いてのアドレスファイルのファイル(メモリ) FILEadd.

追加 FILEsizeFILEadd.

移動backwords(-は増加により-1***CHARsize**)、検査の各CHARsizeバイトのためのおはな改行システムで使用するに達している場合おしておりますの位置の最初の行はファイルです。代わりとなるx1a(26日に、アスキーのためのEOFになることが一つのシステムのエンコーディング)

清掃が必要なもの(変更のfilesizeをタッチすることでそのファイル).

この作品と思うので、いすると新しいパスワードを入力して必要なはじめにお読みのファイルの先頭からのオープンしたばからです。

ここで、別の方法なおぼのファイルをメモリ

p=""
f=open("file")
for line in f:
    line=line.strip()
    print p
    p=line
f.close()

こちらはより一般的なメモリ効率が高いソリューションを最後の'n'ラインスキップするように head コマンド):

import collections, fileinput
def head(filename, lines_to_delete=1):
    queue = collections.deque()
    lines_to_delete = max(0, lines_to_delete) 
    for line in fileinput.input(filename, inplace=True, backup='.bak'):
        queue.append(line)
        if lines_to_delete == 0:
            print queue.popleft(),
        else:
            lines_to_delete -= 1
    queue.clear()
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top