how to append or create list through other python script?
ex:
1.py
list = [['1', '2'], ['3', '4']]
2.py
import 1
1.list.append('5', '6')
then list becomes
list = [['1', '2'], ['3', '4'], ['5', '6']]
If you meant to 'physically' add the '5' , '6'
to the file 1.py
, then you need to open 1.py
file in the other script and modify the text.
Assume this is your 1.py
.
.
. other lines...
list1 = [1,2,3]
.
.
.
.other lines...
If I assume in your 1.py
, there is no other lines that is exactly the same as list1 = [1,2,3]
, then you can do this:
with open('1.py', 'rt') as f:
oldlines = f.readlines()
for index,line in enumerate(oldlines):
if line == "list1 = [1,2,3]":
# find the line with the text you want to change
# You can simply change the text
# but what I did here is create the list called list1
# then append value to it
# then generate the new line and overwrite the orignal line.
exec(line)
list1.append(['5','6'])
oldlines[index] = f'list1 = {list1}'
break
with open('1.py', 'wt') as f:
f.write('\n'.join(oldlines))
Your IDE might complain list1
is undefined, but that's OK because the exec(line)
is creating list1
for you.
If you meant to modify the list you imported from 1.py
while running 2.py
, then you need to change the name of 1.py
to something like file1.py
that doesn't start with number. Because python won't allow module name start with number.
Also you need to change your code slightly:
import file1
file1.list.append(['5', '6'])
Do not call your variables list
, dict
or the like. That being said, you could use
from other_file import lst
lst.append(['5', '6'])
print(lst)
Which would yield
[['1', '2'], ['3', '4'], ['5', '6']]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.