修改我的代码并使用python3将其保存为函数内的文本文件

问题描述 投票:0回答:1

如何使用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
python-3.x function call
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.