0

I'm currently working on a python bot that references variables from different users based on the input from the user. The user enters in the name of a file in the folder, which has a list saved to it. All of the files have the same list name, but each list has different elements saved. The idea is that the files act as accounts for the user, and each one has its own keys saved in the list.

I want to then set a variable to the contents of the list from whatever file the user selected, like so:

import file1
import file2
import file3

filePath = input()
fileContents = filePath.list

This displays an error because the filePath variable is technically a string and does not have a list attribute.

My question is:
How can I set fileContents to the contents of the list that the user chosen file contains?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • Read the file; parse the list. – Scott Hunter Feb 07 '22 at 20:47
  • Does this answer your question? [python get module variable by name](https://stackoverflow.com/questions/22011073/python-get-module-variable-by-name) – splash58 Feb 07 '22 at 20:48
  • 1
    you may find a [json structure](https://stackoverflow.com/a/20199213/4541045) (per user?) or [some database](https://docs.python.org/3/library/sqlite3.html) is much easier to manage – ti7 Feb 07 '22 at 20:53
  • note there are also security concerns with blindly allowing a user to select a file, as they may be able to direct your script to files outside the directory – ti7 Feb 07 '22 at 20:55
  • I'm now wondering if it's possible to write a Python app that accepts plugins at runtime, and the plugins are .DLLs written in C++ – Jack Deeth Feb 07 '22 at 21:06
  • Gabriel: No, it's not possible. A file is simply raw data and isn't really anything until read into memory and converted to some data-structure (or kept simply as a list or array of byte values). – martineau Feb 07 '22 at 21:09

2 Answers2

0

For a single file, you can get the lines in the file with .splitlines() or iterating over it

with open("input.txt") as fh:
    lines = fh.read().splitlines()
with open("input.txt") as fh:
    for line in fh:
        print(line), end="")
ti7
  • 16,375
  • 6
  • 40
  • 68
0

You want to select one of three objects based on user input?

import file1
import file2
import file3

file_lists = {
    "file1": file1.list,
    "file2": file2.list,
    "file3": file3.list,
}

while True:
    selection = input("Select file containing list: ").lower()
    if selection in file_lists:
        break
    print(f"Selection must be one of: {', '.join(file_lists)}")

fileContents = file_lists[selection]
Jack Deeth
  • 3,062
  • 3
  • 24
  • 39