【问题标题】:How to read input file for correct int list? python, list,如何读取输入文件以获取正确的 int 列表?蟒蛇,列表,
【发布时间】:2023-03-08 18:24:01
【问题描述】:

我的输入是一个 int 元素列表,我将列表保存为一个文件(不是更多,也不是更少),到目前为止效果很好。 但是,当将文件作为 int 列表的输入时,我要么得到错误的列表元素,要么得到代码错误。数字可以是任何(正)int,并且是偶数。

文件输入(通过键盘):

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

【问题讨论】:

  • 能否请您粘贴您正在使用的确切代码?
  • 那绝不是 MWE...
  • 所以制作一个 mcve,我们会为您提供帮助。

标签: python list file input


【解决方案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() 的使用,以消除可能的前导/尾随空格和/或换行符。

【讨论】:

  • 第一个解决方案返回错误 [Invalid literal for int() with base 10],第二个工作正常(就我所见)。
  • @Nepumuk 正如我在答案中解释的那样,第一个解决方案仅在文件包含单独行中的数字时才有效。
【解决方案2】:

如果您将列表保存到文件并假设 list_from_file 是已读取的字符串表示形式。使用 ast 评估列表。

import ast
l = ast.literal_eval(list_from_file)

【讨论】:

  • 来自ast docs,这仅适用于“Python 文字结构:字符串、数字、元组、列表、字典、布尔值和无”。如果你想为其他对象提供这样的功能,你应该尝试Pickling
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-11
  • 2018-12-31
  • 1970-01-01
  • 2022-07-06
  • 2014-07-10
  • 1970-01-01
相关资源
最近更新 更多