下面是一个示例代码,实现了你描述的函数功能:
def words_from_file(filename1, filename2):
with open(filename1, 'r') as file1:
content = file1.read()
words = content.split()
with open(filename2, 'w') as file2:
for word in words:
file2.write(word + '\n')
使用时,你可以将要读取的文件名作为参数传递给函数words_from_file()
,并且将要写入的文件名作为第二个参数。例如:
words_from_file('input.txt', 'output.txt')
这将从名为input.txt
的文件中读取文本,将其拆分为单词,并将每个单词写入名为output.txt
的新文件中,每个单词占据一行。