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()
のために[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