2016-05-04 13 views
-1

私はしばらくの間問題があっても、役に立たない問題を解決する方法を探していました。空の行を確認して削除する/その下の行を移動する

私は、以下の機能を持っている:

def showEmail(): 
    f = open("players.txt","r") 
    for line in f: 
     lineList = line.split(";") 
     print "Name: " + lineList[0] + " " + lineList[1] 
     print "Email address: " + lineList[2] 
     print "" 
    f.close() 

示すように、私のファイルはテキストがあります:行を変更する際に空行が必然的に、(私のファイルに表示されたときに問題が発生し

Sam;Tyler;[email protected];0710503687;6;0 
Peter;Bond;[email protected];0798415758;6;0 
Joe;Blogg;[email protected];0749814574;1;60 

プログラムは、変更された行に似た改行を作成し、その行の値を変更します。その後、元の行を削除し、新しい行をコピーして空行にし、すべてを新しい書類にコピーします。これは、示されているとおりに行われます。 :

def writeToFile(): #function to write all new (modified) lines from players to a temps file, deletes players and rename temps to 'players' 
    f = open("players.txt",'r') # Input file 
    t = open("temp.txt", 'w') #Temp output file 

    for line in f: 
     if line != originalInfo: #doesn't write the line that is the same as the original info 
      t.write(line) #writes all lines apart from the original line (one that needs to be deleted) 

    f.close() 
    t.close() 
    os.remove("players.txt") #deletes players 
    os.rename('temp.txt', 'players.txt') #new file with modified info is renamed to players 

ファイルに次が含まれている場合、プログラムはリストインデックスは、それがリストとして空行を考慮するため理にかなっている、束縛の外であることを私に教えてくれます。

Sam;Tyler;[email protected];0710503687;6;0 
Peter;Bond;[email protected];0798415758;6;0 

Joe;Blogg;[email protected];0749814574;1;60 

この問題をどのように修正できますか?ありがとうございました!

def writeToFile(): 
    ... 
    for line in f: 
     if line != originalInfo and line != "\n" # or whatever you're using for an empty line 
      t.write(line) 
    ... 
+1

私は明確ではない:

import csv def showEmail(): with open("player.txt","r") as f: csvFile = csv.reader(f, delimiter=';') for line in csvFile: if line: print("Name: {} {}".format(line[0], line[1])) print("Email address: {}".format(line[2])) print("") 
TigerhawkT3

+0

どの問題を解決したいですか?書き込みサブルーチンは空白行を書き込んではいけませんか、または読み込みサブルーチンは空白行を処理できるはずですか? – manu190466

+0

私はファイルに 'fullName = forename +"; +姓+ ";" + email + ";" +電話+ ";" +除算+ ";" + points + "\ n" '2人のプレイヤーを追加しなければ、それらを並置して別の行に追加しないためです。 – Johny

答えて

1

、あなただけチェックする必要がありますワットの

with open(file) as f_in: 
    return filter(None, (line.rstrip() for line in f_in)) 
+1

'とline.strip()'はここでよく使われるイディオムです。 – TigerhawkT3

+0

そのトリックをした、ありがとう – Johny

0

あなたのファイルは、だから何csvモジュールを使用することについて、CSVファイルのようにフォーマットされている:あなたが変更され、おそらくラインをクリアした場合の行がそれを書き込む前に、空の場合

0

は、私はこの方が好き:Pythonが提供され、以下のexempleを見てファイル書き込み部分 `for line in f:... 'は空白行を作成します。入力ファイルに `'\ n' 'だけで構成された行がない場合、出力には何も表示されません。
関連する問題