If you really do want to edit the source of script2, you can do that—via normal string methods, or regex, or, better, tokenizing or parsing the file. But really, you almost certainly don't want to do that.
If you want some kind of persistent storage across runs of your program, you probably want a separate file. For fancy cases, you may want to use a database like dbm
or sqlite3
, but here, you just have a list of names, so you can probably store them one per line in a simple text file.
There are two tricky bits, but both are pretty easy:
- If you've never run
script1
, there won't be a file yet. So you'll want to handle that case.
- You need to make sure to write newlines (
'\n'
) after each name, and then strip them back off on the other end.
script1.py:
name = input('\n Please enter your name:')
with open('names.txt', 'w') as f:
f.write(name + '\n')
script2.py:
try:
with open('names.txt') as f:
names = [line.rstrip() for line in f]
except FileNotFoundError:
names = []
If you wanted to have a "starting list" of names that worked even before ever calling script1, you'd add a names = ['Name1', 'Name2'] line about the
open, and the change the
names = […]to
names.extend(…)`. But it sounds like you don't want that, so I've made it start with an empty list—the only names are the ones you added to the text file.
One more thing: This look for names.txt
in the current working directory. So if you run your script from some other directory, it won't find the file. If you want to find it in a specific location instead, like /Users/Pergamon256/.config/my-app/names.txt
, that's pretty easy. If you want "wherever is the normal place for my operating system", that's a bit trickier; there are libraries on PyPI that do it for you. If you want the same directory that the scripts are in, there are good answers on SO showing how to do that.