1

I am working at a "cloud server" for myself. I have a tool to list files which are on the server.

flist = os.listdir("C:/Server")
conn.send(bytes("str(flist), "UTF-8"))        

This sends a list to the client, the client converts it to a string. (something like this: [' Arcer.exe', 'Launcher.exe', 'Document.txt']) Now how can I convert the string back into a list?

string = "[' Arcer.exe', 'Launcher.exe', 'Document.txt']"
list = []
list = string.convert  #pseudo method
print(list[0]) #Arcer.exe
print(list[1]) #Launcher.exe

3 Answers 3

2

I would recommend using the json module.

To send the list you can change str(flist) to json.dumps(flist) then on the other end you can reload the list using flist = json.loads(string)

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

Comments

1

You can use literal_eval from ast module:

from ast import literal_eval
string = "[' Arcer.exe', 'Launcher.exe', 'Document.txt']"
newList = literal_eval(string)
print(newList)

Output:

[' Arcer.exe', 'Launcher.exe', 'Document.txt']

If you do not want to use the ast module, another way of doing it is to remove the brackets from your string and then split it in every comma , character as follows:

string = "[' Arcer.exe', 'Launcher.exe', 'Document.txt']"
newList = string[1:-1].replace("'","").split(",")
print(newList)

This will give you the same output as the above:

[' Arcer.exe', ' Launcher.exe', ' Document.txt']

1 Comment

Note that the last won't work if any of the strings have a comma in them.
0

First, never name variables list or string. The first is the name of a built-in class, the second is a module in the standard library.

You should avoid using string representations of Python variables, since reading and writing them are not going to be efficient. But, if you have no other option, you can use ast.literal_eval:

from ast import literal_eval

x = "[' Arcer.exe', 'Launcher.exe', 'Document.txt']"
y = literal_eval(x)

print(y, type(y))

[' Arcer.exe', 'Launcher.exe', 'Document.txt'] <class 'list'>

Comments

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.