Python Forum
Help writing to files - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Help writing to files (/thread-2380.html)



Help writing to files - HummingMaster - Mar-12-2017

the code below the following error
IndexError: list index out of range
can someone help me please! 
import os.path

list_ = []
breaking_string = '  '
print("Start Typing: ")
while True:
    line = input()
    if line == '  ':
        break
    else:
        list_.append(line)

#tf_name = input("Enter text file name: ")
tf_name = 'list'

if os.path.isfile(tf_name) == True:
    file = open(tf_name + '.txt', "a")

else:
    file = open(tf_name + '.txt', "w")

counter = 0
while len(list_) >= counter:
    file.write(list_[counter])
    counter += 1
file.close()



RE: Help writing to files - Ofnuts - Mar-12-2017

List index out of range means that you are using a index in [] which is too big. You are not givigin the full stack trace but there is nly one place in your code where you use that, so have you tried to add a print instruction to check the value/contents of list_ where you index it?

PS: IMHO list_ is a despicable variable name, because list would also be if it where not a reserved name in Python. List of what?

PPS: Looking  at your code, this:
counter = 0
while len(list_) >= counter:
    file.write(list_[counter])
    counter += 1
is much better written:
for l in list_:
    file.write(l)
and circumvents the explicit use of a counter (which, by the way, should go from 0 to len(list_)-1, indices are 0-based in Python).


RE: Help writing to files - wavic - Mar-12-2017

import os.path

file_name = input("Enter the file name: ")

def write_to(file_obj):
    while True:
        line = input()
        if line:
            file_obj.write("{}\n".format(line)) 
        else:
            break
   
if os.path.exists(file_name) and os.path.isfile(file_name):
    with open(file_name, 'a') as f:
        write_to(f)
else:
    with open(file_name, 'w') as f:
        write_to(f)

 
I didn't test it. No lists, no indexing. It just grab the input line and write it to a file


RE: Help writing to files - zivoni - Mar-12-2017

By using >= in line
while len(list_) >= counter:
you are trying to acces list_[len(list_)]. A list a with length n has elements a[0], a[1], .... a[n-1], so using a[n] raises an error.

Use just >, or better, iterate directly over your list with:
for row in list_:
    do stuff with your row