用Python创建文本文件

时间:2017-09-04 12:59:56

标签: python file

是否可以创建一个变量,我可以在其中存储产品列表,而不是使用" 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()

2 个答案:

答案 0 :(得分:1)

我相信你想要完成的是不写一个换行符" \ 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电子表格中打开)

答案 1 :(得分:0)

您可以创建包含所有行和换行符的单个字符串,而不是单独使用writelines编写每一行和换行符,并write

要从项目列表中创建组合字符串,您可以使用join

products = ["Bed", "Couch", "Mirror", "Television", "Tables", "Radio"]
text_file.write("\n".join(products))

(请注意,(a, b, c)会创建一个元组,而[a, b, c]会创建一个列表。您可能想了解这些差异,但在这种情况下无关紧要。)