2017-02-13 76 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: