将文本文件的行与Python相乘。 (需要修复)

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

我被赋予了将文本文件中的行相乘的代码:


这是我的基本文本文件:

Text_1.txt(Open_File)

1
2
3
4

代码:


file = Open_file

with open(file, "r") as f:
    file = f.read()

file_multiply = file * 3

with open('multiply.txt', 'w') as outfile:
    outfile.write(file_multiply)


问题是,multiply.txt(输出文件)看起来像这样:

1
2
3
41
2
3
41
2
3
4

(问题是“ 1”不在行的开头。)您对此有解决方案吗?我提供了代码来帮助您。非常感谢。

python python-3.x multiplying
1个回答
0
投票

您需要在所写的每个项目之间添加换行符。

with open('multiply.txt', 'w') as outfile:
    outfile.write('\n'.join([file]*3))
© www.soinside.com 2019 - 2024. All rights reserved.