【问题标题】:Try except in file opening尝试在文件打开中除外
【发布时间】:2017-02-13 19:28:42
【问题描述】:

我写了一个程序来打开一个文件并打印每一行如果文件不存在创建它并写一些行到它

当文件不在目录中时,它可以正常工作 但是当文件在那里时,它会打开文件读取它->然后将其写入文件,但它应该只读取文件

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

【问题讨论】:

  • 请编辑您的问题并正确缩进。
  • 您将open(filename,'r') 分配给file,并在try 块中的filename 上调用close()
  • 是的,我正在尝试打开文件并读取它,如果文件不存在,那么它应该创建一个新文件并写入它

标签: python-3.x file try-except


【解决方案1】:

在代码的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:

【讨论】:

    猜你喜欢
    • 2013-02-05
    • 1970-01-01
    • 2013-04-25
    • 2016-01-19
    • 1970-01-01
    • 2011-08-17
    • 2014-04-09
    • 1970-01-01
    • 2021-11-02
    相关资源
    最近更新 更多