2017-07-26 52 views
0

我的輸入是一個int元素列表,我把列表保存爲一個文件(不多,不少),目前工作正常。 但是,當涉及到文件作爲我的int列表的輸入,我得到錯誤的列表元素或錯誤的代碼。數字可以是任何(正數)整數,它是偶數。如何讀取正確的int列表的輸入文件? python,list,

輸入文件(鍵盤):

1, 2, 3, 4 

文件內容:

[1, 2, 3, 4] 

從文件輸入後列表:

['[1', '2', '3', '4]'] 

它應該是:

[1, 2, 3, 4] 

我的文件中的元素來自文件需要再次int。

l = list_from_file 
a = 0 
l [ 1 ] = 2 

def take (profil , s , succ) : 
    a = 0 
    j = 0 
    n = 0 
    erf = False 
    if s : 
     print ("\nPut your list in.")# supposed to be a list 
     profil = [ int (x) for x in input ().split (sep = ', ') ] 
     s = False 
    else : 
     profil = input ("\nPut your list in. Again.").split (sep = ', ') 
    erf = check(profil) 
    if not erf : 
     erf = ask (profil , s , succ) 
    return profil , s 

def check(profil) : 
    a = 0 
    b = True 
    n = 0 
    for n in profil [ : ] : 
#  if int (profil [ n ]) < 0 : #Some confusing errors I tried to fix with these possibilities... 
#  if profil [ n ] < 0 : 
     if int (n) < 0 : 
#  if n < 0 : 
      b = False 
      exit 
     a += 1 
    a -= 1 
    if (profil [ -1 ] != profil [ a ]) : 
     b = False 
    return b 
def ask(profil , s , succ) : 
    show(profil , succ) 
    s = check(profil) 
    if s : 
     profil = input ("\nPut your list in.").split (sep = ', ')   
     s = False 
    else : 
     profil = input ("\nPut your list in. Again.").split (sep = ', ') 
# if profil [ 0 ] != 0 : 
#  s = ask 
    return succ, s 

def save(profil , path) : 
    path = input ("Put your path in: ") 
    erf = False 
    if os.path.isfile (path) : 
     inp= input ("File already exists. Overwrite[u], bring as input [e] or ignore[i]?") 
     if inp== 'u' or inp== 'U' : 
      f = open (path, "w") 
      f.write (str (profil)) 
     elif inp== 'e' or inp== 'E' : 
      f = open (path, "r")             
      profil = f.read ().split (sep = ', ') 
     elif inp== 'i' or inp== 'I' : 
      f = open (path, "r")            
      print ("File closed.") 
      f = f.close 
     else : 
      inp= input ("Confusing input. Continue with any key.") 
      return profil 
    else : 
     print ("File made.") 
     f = open (path, "w") 
     f.write (profil) 
     f = f.close 
    return profil 
def bring(path, profil) : 
    path= input ("\nPath: ")  
    f = open (path, "r") 
    profil = f.read().split (sep = ', ') 
# profil = [ int (x) for x in input ().split (sep = ', ') ] 
# profil = profil().read().replace ('[' , '') 
# profil = f.read [ : ].replace (']' , '')#also some variants I tried. 
    f = f.close 
# profil = strrep (profil)#new function I tried to 
    print (profil) 
    return profil 


def delete (path, succ) : 
    erf = False 
    path= input ("Put in deleting path.") 
    if os.path.isfile (path) : 
     os.remove (path) 
       print ("File " + path+ " deleted.") 
     erf = True 
    else : 
     print ("Datei nicht gefunden.") 
    return erf 

inp = input("Please start.") 
while (inp != 'q') and (inp != 'Q') : 
    elif inp == 'N' : 
     inp = input ("and now?") 
    elif inp == 'p' or inp == 'P' : 
     profil , s = take (profil , s , succ) 
     succ = zeigen (profil , succ) 
     if profil [ 0 ] == '0' : 
      print ("Profil not usable..") 
     else : 
      inp = input ("and now?") 
    elif inp == 'z' or inp == 'Z' : 
     succ = show (profil , succ) 
     inp = 'N' 
    elif inp == 's' or inp == 'S' : 
     profil = save (profil , path) 
     inp = 'N' 
    elif inp == 'e' or inp == 'E' : 
     profil = bring(path , profil) 
     print(profil) 
     dif = profil [ 0 ] 
     inp = 'N' 
    elif inp == 'l' or inp == 'L' : 
     succ = delete (path , succ) 
     inp = 'N' 
    else : 
     inp = input ("unknown command. Quit with Q...") 
if (inp == 'q') or (inp == 'Q') : 
    quit () 
+2

您可以粘貼您正在使用的* exact *代碼嗎? –

+0

這將是什麼,但MWE ... – Nepumuk

+0

所以做一個* mcve *,我們會幫助你。 –

回答

1

這裏有幾個選項。

  • 保存每個數字在它自己的行,而不是實際的列表,然後以文件讀取到整數的列表:

    with open(filename) as f: 
        list_of_ints = [int(line.strip()) for line in f] 
    
  • 如果你堅持寫列表原樣在該文件中,可以使用literal_eval(做使用eval):

    from ast import literal_eval 
    
    with open(filename) as f: 
        list_of_ints = literal_eval(f.read().strip()) 
    

請記住我使用strip()來擺脫可能的前導/尾隨空格和/或換行符。

+0

第一個解決方案給出的錯誤[無效的文字爲int()與基地10],第二工作正常(我所看到的)。 – Nepumuk

+0

@Nepumuk正如我在答案中解釋的那樣,第一個解決方案只有在文件包含個別行中的數字時纔有效。 – DeepSpace

0

如果要將列表保存到文件並假定list_from_file是已讀取的字符串表示形式。使用ast來評估列表。

import ast 
l = ast.literal_eval(list_from_file) 
+0

有趣的想法......適用於每種數據類型? – Nepumuk

+0

從[ast文檔](https://docs.python.org/2/library/ast.html),這僅適用於「Python字面結構:字符串,數字,元組,列表,字典,布爾值和無」。如果你想爲其他對象提供這樣的功能,你應該嘗試[Pickling](https://docs.python.org/3/library/pickle.html)。 –