2017-12-07 12 views
0

わかりましたので、基本的に私はこのようなデータを含むテキストファイルにアクセスしようとしている:行のデータを繰り返さずにテキストファイルに書き込む方法は?

John 01 
Steve 02 
Adam 15 

を、私は、それをアクセスする各ラインから整数を分割し、変数「日中それぞれ1から1を引いています"次に、各行から1を減算した後、if文を実行して、行に0が含まれているかどうかを確認します。行に0が含まれている場合は、行全体(番号と名前)を削除してから、次のコードはコンソールで完璧に動作し、名前は完全に印刷され、削除されるだけで、各行が自分のものではなく最後の日の値を印刷しているという事実に問題があります。たとえば、次のように

Steve 14 
Adam 14 

スティーブは01にする必要がありますが、彼はアダムの14私のコードを取ったことは以下に添付されています

global days 
global names 
with open('tracker.txt', 'r') as f: 
    for line in f: 
     days = line.strip()[-2:] 
     names = line.strip()[:-3] 
     days = int(days) - 1 
     print(names +" "+str(days)) 

     if days == 0: 
      f = open("tracker.txt","r") 
      lines = f.readlines() 
      f.close() 
      f = open("tracker.txt","w") 
      for line in lines: 
       if line!=str(names)+ " 01" +"\n": 
        f.write(line[:-3]+ "" + str(days) + "\n") 
      f.close() 
    f.close() 
+2

ネストされたループで同じ変数 '' f''と '' line''を使用していますが、これはエラーが発生しやすくなります。あなたはそれを繰り返している間に '' f''を変えています! –

+0

元の回答はコメントとして投稿されました:私はあなたのコードではあまり掘り下げませんでしたが、その日は2桁を超えて書かれていると仮定しています。 分割を使用することを検討してください。 インスピレーションのためのテストされていない例。 https://paste.ofcode.org/hdFrstgGtWMUCUpKXXCnaP – AsTeR

+0

期待される出力は? –

答えて

1

OKを。あなたが何をしようとしているのか分かりませんが、試してみましょう:

import os 

# The file name of our source file and the temporary file where we keep 
# our filtered data before copying back over source file 
source_file_name = 'tracker.txt' 
temporary_file_name = 'tracker_temp.txt' 

# Opening the source file using a context manager 
with open(source_file_name, mode='r') as source_file: 
    # Opening our temporary file where we will be writing 
    with open(temporary_file_name, mode='w') as temporary_file: 
     # Reading each line of the source file 
     for current_line in source_file: 
      # Extracting the information from our source file 
      line_splitted = current_line.split() 
      current_name = line_splitted[0] 
      current_days = int(line_splitted[1]) 

      # Computing and print the result 
      future_days = current_days - 1 
      print(current_name, future_days) 

      # Writing the name and the computed value 
      # to the temporary file 
      if future_days != 0: 
       output_line = "{} {:02}\n".format(current_name, future_days) 
       temporary_file.write(output_line) 

# After we went through all the data in the source file 
# we replace our source file with our temporary file 
os.replace(temporary_file_name, source_file_name) 

私に教えてください。あなたは何をしようとしていたのですか?いいえ?さて、私たちに詳細を教えてください!

関連する問題