Python Forum
List Won't Write in Text File
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List Won't Write in Text File
#1
import time
global list

list = [] #####This is not the final list, but a list where you add everything to be sorted


def add_to_list(): #####This should loop until you decide you are ready
        

	print("Artist: Album (or type \"done\" if you have finished the list)")
	add = input()

	if add == "done":
		finalize_list()

	else:
		list.append(add + "/n /n")
		add_to_list()


def finalize_list():

    list_sorted = list.sort() ####This list should be alphabetical
    list_final = str(list_sorted) ####This should convert the list to a string due to an earlier error
	
    file = open("LP_list.txt", "w+")
    file.write(list_final)
    file.close()
	
    print("List is now in the text file.")
    time.sleep(3)
	
    exit()



####Actual

add_to_list()
This code writes "None" (without the quotation marks) into the file.

My objective is to first write something, hit enter, append it to the list, then sort the list out alphabetically and then write it into a .txt file.
Reply
#2
Hello,
there are several issues with the code. First off I would start with (albeit not causing an error in this particular code) with a strong recommendation to not use Python reserved keywords and built in function names as variable names - in your case it is list (https://docs.python.org/3.8/library/stdtypes.html#list). Use a different name for the variable. I recommend using an editor with Python syntax highlighter, it will let you know of such occurrences immediately (I use Pycharm IDE, but there are sever lighter alternatives available).

While calling add_to_list() within the function itself will work, it is not recommended (that is recursion). Use a while loop instead.

list.append(add + "/n /n")
Escape character for new line is "\n" (backslash).

list_sorted = list.sort()
calling sort() on a list will sort the list itself ("list" in this case, another reason to change variable name beside previously stated - it is indescriptive). sort() (method of the list class) doesn't return anything, that is why you get "None". So either just call sort(the_list_you_want_to_sort). Or use sorted() builtin function (https://docs.python.org/3.8/library/func...tml#sorted). If you pass a list to this function, it will return the sorted variant of the list.

Assuming you would get a proper list returned, this line
list_final = str(list_sorted)
will just make this list a string of single characters. Try this in the Python console:
str(["a", "b", "c", "d"])
So don't convert the whole list to one big string. The list items are already strings, which is what you want (for outputting to file).

Recommended way to write to file is to use context manager (with). And within the context manager, use a for loop to iterate through the list of items you want to write to file. I would also recommend to append newline characters in this part of code, instead of appending to list of input strings. Example:

 with open("LP_list.txt", 'w') as output_file:
        for item in list_final:
            output_file.write(item + "\n\n")
That was a very good effort on your part. So give it another go, it's just a few changes to make and you will get it working. If you stumble upon errors or have any questions, feel free to post back.
Reply
#3
Thank you so very much! After a little tweaking I got it to work. I am very new to programming, and took a long break from Python to work with another language/program, and am still not too used to using loops etc. I didn't perfectly understand your answer, or rather why it works, due to being so new to this, but I understood enough from your explanation to actually make it work, and now have a working list maker for this little project.

Thanks again!

Here is the final product:

import time

global lp_list
global lp_list_final
global lp_list_sorted
global add

###Duds
add = "not done"

lp_list = [] #####This is not the final list, but a list where you add everything to be sorted

def add_to_lp_list(): #####This should loop until you decide you are ready
        

	print("Artist: Album (or type \"done\" if you have finished the list)")
	add = input()

	if add == "done":
		finalize_lp_list()
	elif add == "":
		print("Input empty, discarding.")
		add_to_lp_list()
	else:
		print("Is this correct? " + add)
		print("Press Enter to confirm, typing anything else will discard.")
		answer = input()
		
		if answer == "":
			lp_list.append(add)
			add_to_lp_list()
		else:
			print("Discarding last.")
			add_to_lp_list()


def finalize_lp_list():
    
    lp_list_sorted = sorted(lp_list) ####This list is the final product, with everything sorted

    lp_list_final = lp_list_sorted

    with open("LP_list.txt", 'w') as output_file:
        for item in lp_list_final:
            output_file.write(item + "\n\n")
	
    print("List is now in the text file.")
    time.sleep(10)
	
    exit()



####Actual

while add != "done":
	add_to_lp_list()
Reply
#4
That's great to hear, well done! ;)

If you require any additional explanations, don't hesitate to ask.

Ah, I forgot to mention in my answer... I recommend to use print() for debugging, it will help find issues quickly.
An example of approach:
1. There's an issue, "None" gets written into file, why is that?
2. Let's see how we write to file (file.write(list_final))
3. Okay, let's see what list_final is, before we write it to the file:

    list_sorted = list.sort() ####This list should be alphabetical
    list_final = str(list_sorted) ####This should convert the list to a string due to an earlier error
    print(list_final)
Here you would get "None" printed. And investigation continues from here... :)
Reply
#5
And just for reference, this is how I imagined the solution. Main points are: to use the while loop instead of recursively calling add_to_lp_list() (the function calls itself - in most cases it's bad practice). Using globals is also a considered bad practice. Prefer passing arguments to functions instead (in the following code it's finalize_lp_list(lp_list), which calls def finalize_lp_list(unsorted_list)


import time


def add_to_lp_list():  #####This should loop until you decide you are ready
    add = "start"
    lp_list = []    #####This is not the final list, but a list where you add everything to be sorted

    while add != "done":
        print("Artist: Album (or type \"done\" if you have finished the list)")
        add = input()

        if add == "done":
            finalize_lp_list(lp_list)
        elif add == "":
            print("Input empty, discarding.")
        else:
            print("Is this correct? " + add)
            print("Press Enter to confirm, typing anything else will discard.")
            answer = input()

            if answer == "":
                lp_list.append(add)
            else:
                print("Discarding last.")


def finalize_lp_list(unsorted_list):
    lp_list_sorted = sorted(unsorted_list)  ####This list is the final product, with everything sorted

    lp_list_final = lp_list_sorted

    with open("LP_list.txt", 'w') as output_file:
        for item in lp_list_final:
            output_file.write(item + "\n\n")

    print("List is now in the text file.")
    time.sleep(10)

    exit()


####Actual

add_to_lp_list()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Read and write active Excel file euras 4 373 Jun-29-2021, 11:16 PM
Last Post: Pedroski55
  Read file, reformat and write new file bryanmartin113 1 348 Jun-08-2021, 09:27 PM
Last Post: Larz60+
  write mariadb table rows query to each file? shams 1 581 Feb-02-2021, 04:10 PM
Last Post: buran
  Read/Write binary file deanhystad 3 741 Feb-01-2021, 10:29 AM
Last Post: Larz60+
  Running A Parser In VSCode - And Write The Results Into A Csv-File apollo 5 1,020 Jan-14-2021, 08:58 PM
Last Post: snippsat
  [split] How to convert the CSV text file into a txt file Pinto94 5 695 Dec-23-2020, 08:04 AM
Last Post: ndc85430
  Is there a way to move text created by turtle.write()? derekered 7 1,141 Dec-16-2020, 09:44 AM
Last Post: itexamples
  Regex text file to store data in list TheSithSiggi 1 428 Dec-03-2020, 04:46 PM
Last Post: bowlofred
  Saving text file with a click: valueerror i/o operation on closed file vizier87 5 1,042 Nov-16-2020, 07:56 AM
Last Post: Gribouillis
  saving data from text file to CSV file in python having delimiter as space K11 1 598 Sep-11-2020, 06:28 AM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020