You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将两个用户输入写入文件并分行?使用\n报错求解决

解决方法

这里有几种不用纠结\n位置就能实现每行一个输入的方式:

方法1:用join拼接字符串后写入

把列表里的两个输入用\n连接成一个字符串,一次性写入文件,还可以在末尾额外加个换行符保证文件最后一行也有换行:

import os
import sys

def userfile():
    text = []
    text.append(input("Enter sentence 1: "))
    text.append(input("Enter sentence 2: "))

    # 用with语句自动管理文件关闭,更安全
    with open(os.path.join(sys.path[0], "sample2.txt"), "w") as file:
        file.write('\n'.join(text) + '\n')

    with open(os.path.join(sys.path[0],"sample2.txt"), "r") as newfile:
        print(newfile.read())

def main():
    userfile()

if __name__ == "__main__":
    main()

方法2:给每个输入添加换行符后存入列表

在获取输入的时候就把\n加上,这样writelines会直接按列表元素写入,每个元素自带换行:

import os
import sys

def userfile():
    text = []
    # 输入后直接加换行符
    text.append(input("Enter sentence 1: ") + '\n')
    text.append(input("Enter sentence 2: ") + '\n')

    with open(os.path.join(sys.path[0], "sample2.txt"), "w") as file:
        file.writelines(text)

    with open(os.path.join(sys.path[0],"sample2.txt"), "r") as newfile:
        print(newfile.read())

def main():
    userfile()

if __name__ == "__main__":
    main()

方法3:用print函数写入文件

利用print函数默认会自动添加换行符的特性,指定输出到文件:

import os
import sys

def userfile():
    text = []
    text.append(input("Enter sentence 1: "))
    text.append(input("Enter sentence 2: "))

    with open(os.path.join(sys.path[0], "sample2.txt"), "w") as file:
        for line in text:
            print(line, file=file)

    with open(os.path.join(sys.path[0],"sample2.txt"), "r") as newfile:
        print(newfile.read())

def main():
    userfile()

if __name__ == "__main__":
    main()

注:原代码缺少os和sys的导入语句,以上修复代码已补充完整。

内容的提问来源于stack exchange,提问作者ChosenLattice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 14:10:27