如何使用python3读取列表并将其保存在一个函数内的文本文件中?请有人帮我
string=["my name is john"," my anniversary is on 04/01/1997","yes","ok"]
def create_file(file_name):
for i in string:
with open(file_name, "w") as input_file:
print(" {}".format(i), file = input_file)
def read_file(file_name):
create_file(file_name)
input_file = open(file_name, 'r')
read_file('file.txt')
with open('file.txt','r') as f:
input_file = f.readlines()
预期输出:(在文本文件中)
my name is john
my anniversary is on 04/01/1997
yes
ok
答案 0 :(得分:1)
根据您的预期输出,这是代码。
string=["my name is john"," my anniversary is on 04/01/1997","yes","ok"]
def create_file(file_name):
with open(file_name, "w") as input_file:
for sentence in string:
# Append new line and write
input_file.write(sentence + '\n')
file_name = "your_filename.txt"
create_file(file_name)