2016-06-16 7 views
0

6文字未満のファイル内の行を取り除き、6文字未満の文字列を含む行全体を削除したいと考えていました。このコードを実行しようとしましたが、テキストファイル全体を削除することになりました。私はこれについてどうやって行くのですか?ファイル行の並べ替え/削除 - Python

コード:事前に

import linecache 

i = 1 
while i < 5: 
    line = linecache.getline('file.txt', i) 
    if len(line) < 6: 
     str.replace(line, line, '') 
    i += 1 

ありがとう!

+1

はこれを再現することはできません。あなたのサンプルコードを実行するとファイルは削除されません。後で 'write'モードでファイルを開いていますか? – roganjosh

答えて

2

かわりlinecacheのopenメソッドを使用するとよいでしょう:

def deleteShortLines(): 
    text = 'file.txt' 
    f = open(text) 
    output = [] 
    for line in f: 
     if len(line) >= 6: 
      output.append(line) 
    f.close() 
    f = open(text, 'w') 
    f.writelines(output) 
    f.close() 
1

は、イテレータの代わりに、非常に長いファイルをサポートするためのリストを完了:

with open('file.txt', 'r') as input_file: 
    # iterating over a file object yields its lines one at a time 
    # keep only lines with at least 6 characters 
    filtered_lines = (line for line in input_file if len(line) >= 6) 

    # write the kept lines to a new file 
    with open('output_file.txt', 'w') as output_file: 
     output_file.writelines(filtered_lines) 
関連する問題