0

My input is a list of int elements where I save the list as a file (not more, not less), which works fine so far. But when it comes to taking the file as an input for my int list, I either get wrong list elements or an error for the code. The numbers can be any (positive) int and it's an even number.

input for file (by keyboard):

1, 2, 3, 4

file content:

[1, 2, 3, 4]

list after input from file:

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

where it should be:

[1, 2, 3, 4]

The elements of my filst from file need to be int again.

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 ( )
3
  • 2
    Can you please paste the exact code you are using? Commented Jul 26, 2017 at 9:10
  • That will be anything but a MWE... Commented Jul 26, 2017 at 9:11
  • So make a mcve and we'll help you. Commented Jul 26, 2017 at 9:11

2 Answers 2

1

You have several options here.

  • Save each number in its own line instead of the actual list, then in order to read the file to a list of ints:

    with open(filename) as f:
        list_of_ints = [int(line.strip()) for line in f]
    
  • If you insist on writing the list as-is to the file, you can use literal_eval (do not use eval):

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

Keep in mind my usage of strip() to get rid of possible leading/trailing spaces and/or new line characters.

Sign up to request clarification or add additional context in comments.

2 Comments

first solution gives error back [Invalid literal for int() with base 10], second works fine (for what I see).
@Nepumuk As I explain in the answer, the first solution will only work if the file contains numbers in individual lines.
0

If you are saving the list to a file and assuming list_from_file is the string representation that has been read. Use ast to evaluate the list.

import ast
l = ast.literal_eval(list_from_file)

1 Comment

From the ast docs, this only works for "Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None". If you want such a functionality for other objects you should try Pickling.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.