gpt4 book ai didi

python - 如何将列表写入txt文件,其中每个项目在一行中不带 "\n"

转载 作者:行者123 更新时间:2023-11-30 22:15:59 24 4
gpt4 key购买 nike

我想将文本项列表写入 .txt 文件,其中每次都写入新行。我试过这个:

items = ['First line', 'Second line' , 'third line']
with open(filepath, "x") as f:
f.writelines(line+"\n" for line in items)

但是当我阅读该文件时,它显示:

['First line\n', 'Second line\n', 'third line\n']

如何编写没有\n 的行?顺便说一句,我尝试过这个:

f.writelines(line for line in items)

但它把所有三项写在一行中:

['First lineSecond line Third line']

最佳答案

\n 表示换行符,需要匹配您的条件每次都换行写入

读取 *.txt 文件后,只需在每一行使用 strip() 即可。

with open(filepath, "r") as f:
lines = f.readlines()

for l in lines:
print(l.strip())

关于python - 如何将列表写入txt文件,其中每个项目在一行中不带 "\n",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50095869/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com