0

Running this code creates file2.txt as expected, but the file is empty. (Note: file1.txt just has the lines of a poem.) Why does this happen? How can I get it to write array a2 to a text file?

import copy

#Open input file, read it into an array, and remove the every other line.
f = open('file1.txt','r')
a1 = f.readlines()
a2 = copy.deepcopy(a1)
f.close
for n in range(len(a1)):
    if n%2 == 0:
        a2.remove(a1[n])

# Open output file and write array into it.
fo = open('file2.txt','w')
fo.writelines(a2)
fo.close
user809695
  • 179
  • 8
  • 4
    `fo.close()` - you are missing parentheses. – jkozera Jan 24 '13 at 23:16
  • Your snippet works fine even without invoking the close method. – Ifthikhan Jan 24 '13 at 23:18
  • Note that you're using no arrays in your code, but lists instead (which is the "proper" way to do it, but it's still worth knowing). – loopbackbee Jan 24 '13 at 23:18
  • Everyone seems to be overlooking the fact that python [automatically closes file descriptors and flushes buffers](http://stackoverflow.com/questions/7395542/python-is-explicitly-closing-files-important) when `fo` goes out of scope (in this case, when the program terminates), so not actually calling close here is meaningless (for the program behaviour, at least) – loopbackbee Jan 24 '13 at 23:26

4 Answers4

2

you need a () after close:

fo.close()

Also consider using the with statement when working with files.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
2

You do realise this is better written as:

from itertools import islice
with open('input') as fin, open('output','w') as fout:
    every_other = islice(fin, None, None, 2)
    fout.writelines(every_other)

Reasoning:

  • File isn't loaded into memory for no reason
  • islice can be used to create a generator for every other line
  • ... which can then be passed to the output's .writelines()
  • the with statement (context manager) automatically closes the files afterwards
  • It's (IMHO) easier to read and understand what the intention is
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • or simply: `with open('text1.txt','r') as f, open('file2.txt','w') as g: g.writelines (x for i, x in enumerate (f) if i % 2)`. I don't understand the magic of itertools if a simple generator does the same trick. – Hyperboreus Jan 24 '13 at 23:20
  • 1
    @Hyperboreus because `enumerate` and modulus are un-necessary overhead handled by `islice` in this case – Jon Clements Jan 24 '13 at 23:25
  • @Hyperboreus also - for change purposes - it's easier to adapt to take every 7th line skipping the first 50, and only up until the 2000th etc... – Jon Clements Jan 24 '13 at 23:32
1

As the comment said, your forgetting to close the file, so the buffer is never flushed.

replace

fo.close

with

fo.close()
Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
0

'close' is a method -- ie. use fo.close() in place of fo.close

Loren Abrams
  • 1,002
  • 8
  • 9