如何在python中从文本文件中读取' n '行并将其存储到另一个文本文件中

fnvucqvd  于 2022-12-20  发布在  Python
关注(0)|答案(1)|浏览(146)

我有一个文本文件**“file_in.txt”。我想读取该文件的前三行,并将从“file_in.txt”读取的这三行写入名为“file_out.txt”的新文件。
写入后,读取
“file_out.txt”**并打印其内容

kjthegm6

kjthegm61#

file_in = "file_in.txt"
file_out = "file_out.txt"
data = ""

# read the first 3 lines of file_in.txt
with open(file_in, 'r') as f:
    for i in range(3):
        data += f.readline()

# write to file_out.txt
with open(file_out, 'w') as f:
    f.write(data)

# read the content of file_out.txt
with open(file_out, 'r') as f:
    content = f.read()
    print(content)

相关问题