2015-08-18 88 views
-3

我堅持,爲什麼words.txt沒有顯示滿格,下面是我的任務必須進行:輸入words.txt文件蟒蛇3

寫代碼來提示輸入文件名用戶,以及嘗試打開提供名稱的文件。如果文件無法打開,則應要求用戶提供另一個文件名;這應該繼續,直到文件被成功打開。

該文件將在每行中包含單詞網格中的一行。編寫代碼依次讀取文件的每一行,刪除換行符並將結果字符串附加到字符串列表中。輸入完成後,網格應顯示在屏幕上。

下面是我執行的代碼,到目前爲止,任何幫助,將不勝感激:

file = input("Enter a filename: ") 

try: 
    a = open(file) 
    with open(file) as a: 
      x = [line.strip() for line in a] 
    print (a) 
except IOError as e: 
    print ("File Does Not Exist") 
+0

您的代碼將不會要求一個文件名反覆,因爲你沒有一個while循環。你不需要'a = open(file)',因爲你在下一行做同樣的事情。這真的是你的代碼? – letsc

+0

不用擔心。即使你甚至沒有提出問題,三個人也已經爲你的作業的第一部分提供了準備好的解決方案。 –

回答

1

注:始終避免使用變量的名字,像filelist因爲它們都建在Python類型

while True: 
    filename = raw_input(' filename: ') 
    try: 
     lines = [line.strip() for line in open(filename)] 
     print lines 
     break 
    except IOError as e: 
     print 'No file found' 
     continue 
0

你需要一個while循環?

while True: 
    file = input("Enter a filename: ") 

    try: 
     a = open(file) 
     with open(file) as a: 
       x = [line.strip() for line in a] 
     print (a) 
     break 
    except IOError: 
     pass 

這將繼續詢問,直到提供有效的文件。

1

下面的實施應該工作:

# loop 
while(True): 
    # don't use name 'file', it's a data type 
    the_file = raw_input("Enter a filename: ") 
    try: 
     with open(the_file) as a: 
      x = [line.strip() for line in a] 
     # I think you meant to print x, not a 
     print(x) 
     break 
    except IOError as e: 
     print("File Does Not Exist")