Appending an asterisk to the end of each line

cs at zip.com.au cs at zip.com.au
Wed Jul 6 01:35:13 EDT 2016


On 05Jul2016 21:37, Python List <python-list at python.org> wrote:
>On 07/05/2016 03:05 PM, Seymore4Head wrote:
>>import os
>>
>>f_in = open('win.txt', 'r')
>>f_out = open('win_new.txt', 'w')
>>
>>for line in f_in.read().splitlines():
>>     f_out.write(line + " *\n")
>>
>>f_in.close()
>>f_out.close()
>>
>>os.rename('win.txt', 'win_old.txt')
>>os.rename('win_new.txt', 'win.txt')
>>
>>I just tried to reuse this program that was posted several months ago.
>>I am using a text flie that is about 200 lines long and have named it
>>win.txt.  The file it creates when I run the program is win_new.txt
>>but it's empty.

Put a counter in your loop:

    count = 0
    for line in f_in.read().splitlines():
        f_out.write(line + " *\n")
        count += 1
    print("count =", count)

Check that it says 200 (or whatever number you expect).

>Not your problem, but you can simplify your read/write loop to:
>
>for line in f_in:
>    f_out.write(line[:-1] + ' *\n')
>
>The 'line[:-1]' expression gives you the line up to but not including the trailing newline.
>Alternately, use:  f_out.write(line.rstrip() + ' *\n')

Importantly for this version, every line _MUST_ have a trailing newline.  
Personally that is what I require of my text files anyway, but some dubious 
tools (and, IMO, dubious people) make text files with no final newline.

For such a file the above code would eat the last character because we don't 
check that a newline is there.

I take a hard line on such files and usually write programs that look like 
this:

    for line in f_in:
        if not line.endswith('\n'):
            raise ValueError("missing final newline on file, last line is: %r" (line,))
        f_out.write(line[:-1] + ' *\n')

Then one can proceed secure in the knowledge that the data are well formed.

I consider the final newline something of a termination record; without it I 
have no faith that the file wasn't rudely truncated somehow. In other words, I 
consider a text file to consist of newline-terminated lines, not 
newline-separated lines.

Cheers,
Cameron Simpson <cs at zip.com.au>



More information about the Python-list mailing list