2017-03-10 22 views
-2

私のプログラムは、プログラムの過程で作成されたデータを取り、最後にこのデータを.txtファイルにエクスポートするかどうかを選択できます。すでに存在するFileNameの値を入力すると、プログラムは現在の.txtファイルを上書きするかどうかをユーザーに確認する必要があります。私のコード中に、すでに存在する値を入力すると、次のコード行の代わりにこのデータが上書きされます。私は他の記事が "a"をappendとして使うと言っているのを見たことがありますが、これがどのようにこのプログラムに関連するかはわかりません。ファイルの上書きを停止する方法はありますか?

(以前の一時ファイルは既にプログラムで作成されています。ユーザーがデータのエクスポートを選択した場合、そのファイルの名前は変更されます)。

def export(): 
    fileName = input(FileNameText) 
    exist = os.path.isfile(fileName) 
    if exist == True: 
     print("This file name already exists.") 
     while True: 
      try: 
       overWrite = input("Would you like to overwrite the file? Y = yes, N = no\n") 
       if overWrite == "Y": 
        break 
       if overWrite == "N": 
        export() 
       else: 
        invalidInput() 
      except: 
       invalidInput() 
     os.rename("temp.txt",fileName+".txt") 
    if exist == False: 
     os.remove("temp.txt") 
+1

あなたのコードを正しくインデントしてください –

+0

宛先ファイルがすでに存在する場合、 'os.rename'は失敗します。 'shutil.move' –

+1

ユーザがこのスクリプトを選択(上書きするかどうか)しても、どんな場合でもos.renameで行を評価する必要があります。ここで最初からロジックを考え直すべきです –

答えて

2

は、これがうまく実行する必要があります。

import os 

while True: 
    filename = input('Provide the file path::\n') 
    if os.path.isfile(filename): 
     overwrite = input('File already exists. Overwrite? Y = yes, N = no\n') 
     if overwrite.lower() == 'y': 
      # call the function that writes the file here. use 'w' on the open handle 
      break 
0

をお使いの実行フローを確認してください - あなたの `break文をループの外にあなたを送信し、後の最初の文ループはあなたのファイルを上書き:

while True: 
     try: 
      overWrite = input("Would you like to overwrite the file? Y = yes, N = no\n") 
      if overWrite == "Y": 
       # this will send you out of the loop 
       # to the point marked "here" 
       break 
      if overWrite == "N": 
       export() 
      else: 
       invalidInput() 
     except: 
      invalidInput() 

    # here 
    os.rename("temp.txt",fileName+".txt") 
関連する問題