Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing files in python the correct way

I have a function that writes the content of list into a text file. For every element in the list, it writes the element into the text file, each having it's own new line.

def write_file(filename):
    name_file = filename
    filename = open(name_file, 'w')

    for line in list:
        if line == len(list)-1:
            filename.write(line)
        else:
            filename.write(line+'\n')
    filename.close()

i tend to notice a mistake where an empty newline is generated at the final line of a text file and I'm wondering if I am writing the file correctly?

Let's say my list contains [1,2,3,4] and writing it to the text file would give me

1
2
3
4
#in some cases, an empty newline is printed here at the end

I have no idea how to check if the write function is generating an extra line in the end due to the '\n' so I'll appreciate if anyone could give me some feedback.

like image 937
Maxxx Avatar asked Aug 10 '26 18:08

Maxxx


2 Answers

Instead of writing to the buffer so many times, do a .join, and write the result once:

with open(filename, 'w') as fp:
    fp.write('\n'.join(your_list))
like image 67
hjpotter92 Avatar answered Aug 12 '26 12:08

hjpotter92


Update:

@John Coleman has pointed out a misunderstanding. It seems that the last line should not have any new line character. This can be corrected by using enumerate() to provide a line count, checking whether it's the last line when printing, and varying the line end character accordingly:

def write_file(filename, data):
    with open(filename, 'w') as f:
        for line_no, item in enumerate(data, 1):
            print(item, file=f, end='\n' if line_no < len(data) else '')

This is not as elegant as using \n.join(data)` but it is memory efficient for large lists.

Alternative to join() is:

def write_file(filename, data):
    with open(filename, 'w') as f:
        print(*data, file=f, sep='\n', end='')

Original answer:

Why not simply use print() and specify the output file?

def write_file(filename, data):
    with open(filename, 'w') as f:
        for item in data:
            print(item, file=f)

Or more succinctly:

def write_file(filename, data):
    with open(filename, 'w') as f:
        print(*data, file=f, sep='\n')

The former is preferred if you have a large list because the latter needs to unpack the list to pass its contents as arguments to print().

Both options will automatically take care of the new line characters for you.

Opening the file in a with statement will also take care of closing the file for you.

You could also use '\n'.join() to join the items in the list. Again, this is feasible for smallish lists. Also, your example shows a list of integers - print() does not require that its arguments first be converted to strings, as does join().

like image 35
mhawke Avatar answered Aug 12 '26 12:08

mhawke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!