2017-09-04 94 views
0

是否可以創建一個變量來存儲產品列表,而不是使用「行」變量。當創建一個文本文件在Python中創建文本文件

#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() 
+0

你的意思是'lines = text_file.readlines()'也許? –

+0

@ Jean-FrançoisFabre不,我想知道是否可以在創建此列表時使用其他變量 lines =(「Bed」,「\ n」,「Couch」,「\ n」,「Mirror」, 「\ n」,「電視」,「\ n」「表格」,「\ n」,「收音機」) – Charisma

+1

我真的不知道你的意思。您可以根據需要創建儘可能多的變量。 –

回答

0

而不是寫每一行,換行,單獨使用writelines,您可以創建一個包含所有行一個字符串和換行符write這一點。

爲了從項目列表創建組合字符串,您可以使用join

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

(請注意,(a, b, c)創建一個元組,而[a, b, c]創建一個列表,你可能想了解的差異,但在這種情況下,它並不重要。)

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 =打開(「productlist.txt」,「W」) 到 text_file =打開(「productlist.txt」,「A」)

如果一個文本文檔不是你的列表中選擇最佳的格式,你可以考慮exporting to a csv file(您可以在Excel電子表格中打開)

+0

這使得這麼多的意義,它的可讀性更強,使用時(和[當給變量賦值時有區別 – Charisma

+0

是的,@ mkrieger1解釋如下在他的答案中,使用(產品)將產生一個元組,而[產品]將產生一個列表。我會做一個谷歌搜索並瞭解其中的差別 –

+0

爲什麼不用'with open()'btw? – SitiSchu