gpt4 book ai didi

python - 在 Python 中创建文本文件

转载 作者:太空宇宙 更新时间:2023-11-03 14:48:53 25 4
gpt4 key购买 nike

是否可以创建一个变量来存储产品列表,而不是使用“lines”变量。创建文本文件时

#creating a textfile 

text_file= open("productlist.txt", "w")

lines = ("Bed","\n","Couch","\n","Mirror","\n","Television","\n"
"Tables","\n","Radio")


text_file.writelines(lines)
text_file.close()

text_file = open("productlist.txt")
print(text_file.read())
text_file.close()

最佳答案

我相信您想要完成的任务是不要每次都在其中写入换行符“\n”,对吧?只需将代码放入循环即可:

#Create text file
text_file = open("productlist.txt", "w")

#Enter list of products
products = ["Bed", "Couch", "Mirror", "Television", "Tables", "Radio"] #Formerly "lines" variable

#Enter each product on a new line
for product in products:
text_file.writelines(product)
text_file.writelines('\n')

#Close text file for writing
text_file.close()

#Open text file for reading
text_file = open("productlist.txt")
print(text_file.read())

#Close text file
text_file.close()

如果您决定要附加到文档而不是每次都覆盖它,只需更改 text_file= open("productlist.txt", "w")到 text_file= open("productlist.txt", "a")

如果文本文档不是您列表的最佳格式,您可以考虑 exporting to a csv file (您可以在 Excel 电子表格中打开)

关于python - 在 Python 中创建文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46037641/

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