1

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()
Mazdak
  • 105,000
  • 18
  • 159
  • 188
Charisma
  • 43
  • 1
  • 4

2 Answers2

1

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)

In_Circ
  • 83
  • 9
  • this makes so much sense and its much more readable, is there a difference when using ( and [ when assigning values to a variable. – Charisma Sep 04 '17 at 13:42
  • Yes, @mkrieger1 explains below in his answer that using (products) will result in a tuple whereas [products] will result in a list. I would do a google search and learn the difference – In_Circ Sep 04 '17 at 13:45
  • Why not use `with open()` btw ? – SitiSchu Sep 04 '17 at 13:50
  • I have the below code and Im trying to remove a line from the above productlist.txt file but the problem is I still see everything and nothing has been removed `import sys f=open("productlist.txt", "r") lines= f.readlines() for line in lines: sys.stdout.write(line) f.close() del lines[2] f=open("productlist.txt", "r") lines= f.read() print(lines) f.close()` – Charisma Sep 04 '17 at 14:23
0

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.)

mkrieger1
  • 19,194
  • 5
  • 54
  • 65