I'm trying to make a code that would take the information a user inputs and adds it permanently to a different file's variable:
main.py:
text = "hello world"
f = open("Testfile.py", "a ")
f.write(text)
Testfile.py:
w = ["bob", "joe", "emily"]Hello World
how can I make it so that "Hello World" would appear in w such as
w = ["bob", "joe", "emily", "Hello World"]
Edit:
what if w is a library such as
w = {"bob": 0, "joe": 0, "emily" : 0}
and I want to add "Hello World" : 0
to it
CodePudding user response:
Is it really necessary to store the content of you array to a python file? You could store it into a yaml file for instance instead, and you a yaml library to write and read the content to/from that file.
import yaml
import os
def load_yaml(filename):
with open(filename, 'r') as fp:
y = yaml.safe_load(fp)
return y
def save_yaml(content, filename):
if os.path.exists(filename):
os.remove(filename)
with open(filename, 'w') as fp:
yaml.safe_dump(content, fp, default_flow_style=False)
w = ["bob", "joe", "emily"]
save_yaml(w, "data.yaml")
w.append("hello world")
save_yaml(w, "data.yaml")
content = load_yaml("data.yaml")
print(content)
CodePudding user response:
I would strongly recommend not modifying a python file programmatically. You will likely be able to accomplish the same task by storing your list in a text file and having any program read the text file and build the list. There are other file formats you could use for more complicated tasks, but for simply putting strings in a list this code is sufficient. Some kind of full-on database would be best for a real-world application.
test.txt:
bob
joe
emily
main.py:
def read_file():
f = open('test.txt', 'r')
lines = f.readlines()
lines = [line.strip() for line in lines] #removes the '\n' character at the end of each line
print(lines)
f.close()
def append_file(item):
f = open('test.txt', 'a')
f.write(item)
f.write('\n')
f.close()
read_file()
append_file("Hello World")
append_file("test")
read_file()
Also as a bonus, you can use with
to manage file objects more concisely.
def read_file():
with open('test.txt', 'r') as f:
lines = f.readlines()
lines = [line.strip() for line in lines] #removes the '\n' character at the end of each line
print(lines)
def append_file(item):
with open('test.txt', 'a') as f:
f.write(item)
f.write('\n')