Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #28285

Re: [2.5.1] Read each line from txt file, replace, and save?

From Terry Reedy <tjreedy@udel.edu>
Subject Re: [2.5.1] Read each line from txt file, replace, and save?
Date 2012-09-02 14:04 -0400
References <uec64893qomnns4ih36319m47bkkpqr488@4ax.com> <nid648l7k80oli3t84okl598s5fqkgascn@4ax.com>
Newsgroups comp.lang.python
Message-ID <mailman.97.1346609082.27098.python-list@python.org> (permalink)

Show all headers | View raw


On 9/2/2012 6:36 AM, Gilles wrote:
> On Sun, 02 Sep 2012 12:19:02 +0200, Gilles <nospam@nospam.com> wrote:
> (snip)
>
> Found it:
>
> #rewrite lines to new file
> output = open('output.txt','w')
>
> for line in textlines:
> 	#edit each line
> 	line = "just a test"
> 	output.write("%s" % line)
>
> output.close()

If you process each line separately, there is no reason to read them all 
at once. Use the file as an iterator directly. Since line is already a 
string, there is no reason to copy it into a new string. Combining these 
two changes with Mark's suggestion to use with and we have the following 
simple code:

with open('input.txt', 'r') as inp, open('output.txt', 'w') as out:
     for line in inp:
         out.write(process(line))

where for your example, process(line) == 'just a test\n'
(you need explicit line ending for .write())

-- 
Terry Jan Reedy

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

[2.5.1] Read each line from txt file, replace, and save? Gilles <nospam@nospam.com> - 2012-09-02 12:19 +0200
  Re: [2.5.1] Read each line from txt file, replace, and save? Gilles <nospam@nospam.com> - 2012-09-02 12:36 +0200
    Re: [2.5.1] Read each line from txt file, replace, and save? Mark Lawrence <breamoreboy@yahoo.co.uk> - 2012-09-02 12:02 +0100
    Re: [2.5.1] Read each line from txt file, replace, and save? Terry Reedy <tjreedy@udel.edu> - 2012-09-02 14:04 -0400
      Re: [2.5.1] Read each line from txt file, replace, and save? Gilles <nospam@nospam.com> - 2012-09-05 14:52 +0200

csiph-web