How would I call upon a list in an external .txt file in Python and be able to use it in my code and add to it?
-
1*external `list`* meaning? `list` defined in another Python file? – Ma0 Jul 18 '17 at 15:51
-
1This would require a lot more information, starting with the format that the list is currently in. As it stands, the question is too broad to give any useful suggestions. Please see [How to ask](https://stackoverflow.com/help/how-to-ask) for an outline on the kind of information to include in your question. – roganjosh Jul 18 '17 at 15:52
2 Answers
There are many ways to do this. Here is one very simple way (for pure demo purposes):
(within the same directory, create two files)
File 1: mydata.py
- this store the "external list"
dummy = [1, 2, 3]
File 2: main_program.py
- this import the "external list" and print it
from mydata import dummy
print(dummy)
# print out [1, 2, 3]
Then just run the python code like this:
python main_program.py
Reference: Importing variables from another file

- 2,726
- 4
- 27
- 36
It isn't clear what you mean when you say external list, so I'm going to assume that you mean data stored in a text file. To read from a file, use Python's file methods. If you want to read the entire contents of the file, use the read method of the file object.
f = open("mylist.txt", "r")
contents = f.read()
f.close()
With a list, however, it may be useful to read the file one line at a time. In this case, you can either use the readline method
f = open("mylist.txt", "r")
line1 = f.readline()
line2 = f.readline()
f.close()
or loop over the file object
f = open("mylist.txt", "r")
for line in f:
#do something with line
f.close()
To modify the file, open the file in write or append mode and write to it.
f = open("mylist.txt", "w") #Overwrites any data in the file
f.write("foo\n")
f.write("bar\n")
f.close()
f = open("mylist.txt", "a") #Preserves and adds to data in the file
f.write("foo\n")
f.write("bar\n")
f.close()

- 378
- 4
- 17