2017-12-28 13 views
0

次のプログラムでは、ファイルをelseブロックに閉じたいので、tryブロックの外側にfptrを宣言しました。しかし、 "AttributeError: 'NoneType'オブジェクトには 'close'属性がありません。あなたはのOpenFile()でCreateNewFile()にファイルオブジェクトを返すされていません。この場合にはtryブロックにtryブロックのファイルポインタにアクセスする方法elseブロックpython

def openFile(fileName): 
    fptr = open(fileName,"r") 
    fptr.close() 

def creatNewFile(): 
    fileName = input("Enter file name : ") 
    fptr = open(fileName,"w") 
    fptr.close() 

def main(): 
    fileName = input("Enter file name with extension: ") 
    fptr = 0 
    try: 
     fptr = openFile(fileName) 
    except Exception as ex: 
     print("File is not exist") 
     choice = input("Do you want to create new file(Y/N)") 
     if((choice == 'N') or (choice == 'n')): 
      print("Exiting program"); 
      exit(0) 
     elif((choice == 'Y' or choice == 'y')): 
      creatNewFile() 

     else : 
      print("Invalid choice, exiting program ") 
    else:    
     fptr.close(); 

main() 
+0

のために[os.path.exists](https://docs.python.org/3/library/os.path.html#os.path.exists)の使用を検討してくださいファイル/ディレクトリが存在するかどうかをチェックし、[with文](https://docs.python.org/3.6/tutorial/inputoutput.html#reading-and-writing-files) – Georgy

答えて

1

開いていたファイルをクローズする方法。

これを試してみてください:

def openFile(fileName): 
    fptr = open(fileName, "r") 
    return fptr 


def creatNewFile(): 
    fileName = input("Enter file name : ") 
    fptr = open(fileName, "w") 
    return fptr 


def main(): 
    fileName = input("Enter file name with extension: ") 
    fptr = 0 
    try: 
     fptr = openFile(fileName) 
     fptr.close() 
    except Exception as ex: 
     print("File is not exist") 
     choice = input("Do you want to create new file(Y/N)") 
     if ((choice == 'N') or (choice == 'n')): 
      print("Exiting program") 
      exit(0) 
     elif ((choice == 'Y' or choice == 'y')): 
      newfptr = creatNewFile() 
      newfptr.close() 
     else: 
      print("Invalid choice, exiting program ") 


main() 
関連する問題