In first.py, change your code like this.
w mode is for write operation. In each iteration of for loop you are overwriting the last content and writing the new one. So input.txt was having ef in that (finally).
list=["ab","cd","ef"]
for i in list:
with open("input.txt", "a+") as input_file:
print("{}".format(i), file = input_file)
And now you will get what you expected from this. Now input.txt will have the following unlike with your case.
ab
cd
ef
Note: But if you will will run first.py 2nd time, it will continue to add as a+ creates file if file does not exist otherwise it appends.
For better working of this code use os.path module's exists() function.
And if you want to call the code available in first.py then wrap it inside the function. Then import that function in second.py and call.
For example
First make sure first.py and second.py are in the same directory.
first.py
def create_file(file_name):
list=["ab","cd","ef"]
for i in list:
with open(file_name, "a+") as input_file:
print(" {}".format(i), file = input_file)
second.py
from first import create_file
def read_file(file_name):
# Create file with content
create_file(file_name)
# Now read file content
input_file = open(file_name, 'r')
for line in input_file:
if "ef" in line:
print(line)
read_file('input.txt')
Open terminal, navigate to this directory, run python second.py.
https://www.learnpython.org/en/Module... | https://www.digitalocean.com... | https://www.programiz.com/pytho... would be the helpers for you if you want to read and try how to create module/package in Python.
Update: The above has a problem as you have mentioned in comment, in each each run, it will append the content. Let's fix it with a little change to first.py as follows.
import os
def create_file(file_name):
l = ["ab", "cd", "ef"]
if os.path.exists(file_name): # If file `input.txt` exists (for this example)
os.remove(file_name) # Delete the file
for i in l:
with open(file_name, "a+") as input_file:
print(" {}".format(i), file = input_file)
That is it (update in comment if you are stuck).
listis a reserved word in python. When you assign a value to it you lose all of that word's functionality. Basically if you tried callinglist(something)you will get aTypeError. DO NOT use keywords or reserved words as variable names!