2017-03-10 74 views
-2

我的程序需要在程序过程中创建的数据,最后用户可以选择是否将这些数据导出为.txt文件。如果为已存在的FileName输入一个值,程序应该询问用户是否要覆盖当前的.txt文件。在我的代码中,如果输入已存在的值,它将覆盖此数据而不是跟随下一行代码。我看过其他文章说要用“a”来追加,但我不明白这与这个程序有什么关系。如何停止覆盖文件?

(临时文件已经在程序的早期创建,如果用户选择导出数据,文件只是重命名,如果用户不想,它会删除文件。)

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")