在
first.py
,像这样更改代码。
w
模式用于写入操作。在for循环的每个迭代中,您将覆盖最后一个内容并编写新内容。所以
input.txt
正在
ef
最后。
list=["ab","cd","ef"]
for i in list:
with open("input.txt", "a+") as input_file:
print("{}".format(i), file = input_file)
现在你会得到你所期望的。现在
输入文件
会有以下不同于你的情况。
ab
cd
ef
注:
但如果你愿意的话
第一个.py
第二次,它将继续添加为
a+
如果文件不存在,则创建文件,否则将追加文件。
为了更好地处理此代码,请使用
操作系统路径
模块的
exists()
功能。
如果你想调用
第一个.py
然后将其包装在函数中。然后将该函数导入
second.py
打电话来。
例如
首先确保
第一个.py
和
第二年
在同一个目录中。
第一个.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)
第二年
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')
打开终端,导航到此目录,运行
python second.py
.
https://www.learnpython.org/en/Module...
|
https://www.digitalocean.com...
|
https://www.programiz.com/pytho...
如果你想阅读并尝试
如何创建模块/包
在巨蟒中。
更新
:上面有一个问题,正如您在comment中提到的,在每次运行时,它都会附加内容。我们把它改一下
第一个.py
如下所示。
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)
就是这样(如果你卡住了,请在评论中更新)。