2017-02-13 68 views
-2

我寫了一個程序打開文件和打印每一行,如果該文件不存在創建它,並寫一些線將其嘗試除了在文件打開

它完美的作品時,該文件不存在目錄 但是當文件有它打開的文件中讀取它 - >然後將其寫入文件,但它只能讀取文件

print("We will do some file operation") 
filename=input("enter a file name: ") 
try: 
file=open(filename,'r') 
print("File opened") 
for line in file: 
    print(line) 
filename.close() 
print("file cosed") 

except: 
file=open(filename,'w') 
print("File created") 
for i in range(15): 
    file.write("This is line %d\r\n"%(i)) 
print("write operation done") 
file.close() 
+1

請編輯您的問題,並正確縮進它。 –

+1

您將'open(filename,'r')'分配給'file',並在'try'塊的'filename'上調用'close()'? – Trelzevir

+0

雅我想打開文件,並閱讀它,如果文件不存在,那麼它應該創建一個新的文件,並寫入它 –

回答

0

在你的代碼的try塊,設置file=open(filename,'r')。但是在該區塊的末尾,您嘗試filename.close()。你想關閉文件,而不是輸入字符串。

try: 
    file=open(filename,'r') 
    print("File opened") 
    for line in file: 
     print(line) 
    file.close()    #wrong variable name on this line 
    print("file cosed") 

您的縮進在您發佈的問題中也是錯誤的,它應該如上所述。 毯子的例外也不理想,你應該使用:

except IOError: