-1

I have an array

['Name1', 'Name2', 'Name3', ...., 'NameN'] 

this array is stored in a .txt file, exactly like that.

Now in my code, I am trying to compare that array in the file with another array that's not stored in a file.

When I read the txt file array the type is a string, if I convert it to list I will get this

["['Name1'", " 'Name2' ", " 'Name3' ", ..... 'NameN']"]

Just curious, how do I read that txt file array and make it look like ['Name1', 'Name2', 'Name3', ...., 'NameN']

Thanks

derpirscher
  • 14,418
  • 3
  • 18
  • 35

3 Answers3

0

Disclaimer: You should be aware about the security of Python eval() on untrusted strings!

Example of eval() function:

input_string="['Name1', 'Name2', 'Name3','NameN']"
result=eval(input_string)
print(result)

Output:

['Name1', 'Name2', 'Name3', 'NameN']
AziMez
  • 2,014
  • 1
  • 6
  • 16
0

When you're reading files, Python automatically transforms text file's contents to a list of strings. If you use readlines() for example, you will create a list of strings, each string from that list being a single line of text from your text file.

Python by itself cannot convert string to a list, what you could do is use ast module, then use ast.literal_eval() function to transform input string to actual data type, note that the string has to be a correct Python data type (list, set, tuple or dictionary), if it's not the interpreter will raise an exception.

ast.literal_eval() function takes any string as parameter.

Example:

import ast

with open('myfile.txt', 'r') as f:
   f_contents = f.readlines()
   lists = []
   
   for line in f_contents:
        lists.append(ast.literal_eval(line))

This piece of code will:

  1. Open your text file and read contents
  2. Each line of text inside the file will be added as an string to f_conents list
  3. Create an empty list of lists, this will contain all valid lists from your f_contents list
  4. For loop that will read through every line of text from f_contents and convert it from a string to a proper Python list using ast.literal_eval()

EDIT: Forgot to mention, there's also eval function as mentioned by another answer, however eval() is considered to be unsafe. ast.literal_eval() accepts only strings that are identical to a data type in Python, it will throw an exception if input is not a list, dict or tuple; where eval can interpret any command whether it's malicious or not, it's functionality can be abused so it's recommended to not use with user input.

0

Array.txt -> ['Name1', 'Name2', 'Name3']

yourArray -> ['Name1', 'Name2', 'Name3']

def compareArrays(StoredArrayLocation,yourArray):
    with open(StoredArrayLocation, "r") as f:
        storedData = f.read()    
        x=[]
        x=storedData
        f.close()
        #print(x)
    if x==yourArray:
        return True
    else:
        return False

 

compareArrays("Array.txt",yourArray)

Output: True