-1

Hi I am reading lines from a file which has the details of variables that I need to further run my program. The code I am using to read the lines from the file is as follows:

file_name="<file path>/inputPS05.txt"
file=open(file_name)
lines = [line.strip(" \n ''") for line in open(file_name)]

Please refer the screenshot below: Jupyter Code Sample

lines[0] gives a string output which is expected but I want to convert them into variables. How can I achieve that?

I am pulling index items from the list but I am unable to change it to variables and values.

matszwecja
  • 6,357
  • 2
  • 10
  • 17
noob
  • 47
  • 5
  • 1
    [Please do not upload images of code/data/errors.](//meta.stackoverflow.com/q/285551) – matszwecja Jul 06 '23 at 08:35
  • What are you hoping to achieve by converting them "into variables"? What is it that you can't currently do? – Mathias R. Jessen Jul 06 '23 at 08:39
  • 1
    Essentially you have code stored in that file, not data. So you're looking at `eval`. Or maybe, if your "code" is confined to some specific subset of possible expressions, maybe it's a valid [INI](https://docs.python.org/3/library/configparser.html) or something like that. – deceze Jul 06 '23 at 08:40
  • 4
    Regardless of what all the answers suggest, **don't use eval/exec**. It's bad. – matszwecja Jul 06 '23 at 08:49
  • @matszwecja what would you suggest I use? – noob Jul 06 '23 at 09:23
  • 1
    @noob First thing I'd think about is fixing the actual input file to be some format better suited for storing data. What is it this file actually? Is it a valid Python script? – matszwecja Jul 06 '23 at 09:25

2 Answers2

1

You can use the exec keyword, although it is not recommended for security reasons.

for line in lines:
    exec(line)

It is rather recommended to parse the line and fill a dict of values for example.

matleg
  • 618
  • 4
  • 11
1

Using exec will work, but is generally unsafe, as you don't always know what code you might be running. If it's your code, and you know everything in the file, then you can do this:

for line in lines:
    exec(line)

Further issues with your code:

You are setting the file variable, but then not using it in your loop.

Your code should read:

lines = [line.strip(" \n ''") for line in file]

Even better, you should use a context manager:

with open(file_name) as file:
    lines = [line.strip(" \n ''") for line in file]

This will handle closing of the file for you.

Mitchell
  • 101
  • 5