簡體   English   中英

python 3.6中的縮進錯誤

[英]Indentation Error in python 3.6

當我在IDLE中運行此代碼時,出現SyntaError(預期為縮進塊)問題是我看不到任何縮進問題。 代碼的作用:讀取“ cities.txt”文件(帶有字符串行),然后在每一行進行枚舉后將這些行復制到“ out.txt”中

try:
    with open('cities.txt', 'r+') as inp:
except FileNotFoundError:
    print('File not found')
except:
    print('Error')
else:
    try:
        with open('out.txt', 'a+') as out:
    except FileNotFoundError:
        print('File not found')
    except:
        print('Error')
    else:
        for i, line in enumerate(inp):
            out.write(str(i+1)+': '+line)
            print(str(i+1)+': '+line, end='\n')

with x as y:應該緊跟一個縮進的代碼塊,該代碼塊可以完成您想要使用的資源-基本上是您在else塊中擁有的

為了確保邏輯和格式,您應該這樣編寫代碼:

try:
    with open('out.txt', 'a+') as out:
        for i, line in enumerate(inp):
            out.write(str(i+1)+': '+line)
            print(str(i+1)+': '+line, end='\n')
except FileNotFoundError:
    print('File not found')
except:
    print('Error')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM