Charisma
Charisma

Reputation: 43

Creating text files in Python

Is it possible to create a variable in which I can store a list of products instead of using "lines" variable. when creating a text file

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

Upvotes: 1

Views: 5505

Answers (2)

In_Circ
In_Circ

Reputation: 83

I believe what you're trying to accomplish is to not write a line break "\n" in there every time, right? Just throw your code into a loop:

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

If you ever decide you want to append to your document rather than overwrite it every time, just change text_file= open("productlist.txt", "w") to text_file= open("productlist.txt", "a")

If a text document isn't the best format for your list, you might consider exporting to a csv file (which you can open in an excel spreadsheet)

Upvotes: 1

mkrieger1
mkrieger1

Reputation: 23264

Instead of writing each line, and the line breaks, individually using writelines, you can create a single string containing all the lines and the line breaks, and write that.

In order to create the combined string from a list of items, you can use join.

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

(Note that (a, b, c) creates a tuple, while [a, b, c] creates a list. You may want to learn about the differences, but in this case it doesn't matter.)

Upvotes: 0

Related Questions