0

Here is a beginners question:

I made a function that reads a txt file (selected by the user) and makes a list of many numbers contained in the file, called A. I called this function open_file. Then I want to change the name of that list with the original name of the file, plus "_values"

My try

file_name = raw_inpunt('Give the name of the file:') # the user chooses the file
open_file (file_name) #A list is created

file_name +'_'+'values' = A

This doesn't seem to work. Any ideas?

Shubhanshu Mishra
  • 6,210
  • 6
  • 21
  • 23
  • 1
    Why do you need to change the name of the variable to match the filename? Wouldn't that make it harder for the rest of the code to use the variable? If you really need to reference data by a name, consider using a `dict` instead. – Shawn Chin Oct 30 '12 at 10:02
  • there are multiple issues in your code: typo in `raw_input`, you don't save the returned value of `open_file()` so `A` is probably undefined, `"something" = anything` is not valid Python. How do you want to use `*_values` variable later? – jfs Oct 30 '12 at 10:06

2 Answers2

2

If you will be doing this to a lot of files it would be better to store the lists in a dictionary rather than making a new variable for each.

results = {}
....
file_name = raw_input('Give the name of the file:') # the user chooses the file
open_file(file_name) #A list is created
results[file_name] = A
Tim
  • 11,710
  • 4
  • 42
  • 43
-1

You can try using:

vars()[file_name+"_values"] = A

The reason it is not working because you are trying to save a list in a string.

Basically file_name+"_"+"values" is a string a not a variable. Hence you will get an error.

However I would highly suggest you saving the list of values for each filename in a dictionary.

values = dict()
values[file_name] = A

This is a more efficient way of storing values.

Shubhanshu Mishra
  • 6,210
  • 6
  • 21
  • 23