Python thinks file is empty

Tim Chase python.list at tim.thechases.com
Mon Nov 5 10:57:15 EST 2007


loial wrote:
> I am writing a file in python with writelines
> 
> f = open('/home/john/myfile',"w")
> f.writelines("line1\n")
> f.writelines("line2\n")
> f.close()
> 
> But whenever I try to do anything with the file in python it finds  no
> data. I am trying ftp, copying the file...the resultant file is always
> 0 bytes, although if I look at the original file on the unix command
> line, its fine
> 
> e.g.
> 
> shutil.copyfile('/home/john/myfile', '/home/john/myfile2')
> 
> Any ideas what the problem is?

A failure to copy/paste the lines as you had them?  Or perhaps 
accessing the file before it's been closed/flushed?  Or perhaps 
you're opening it in write-mode after you've closed the file 
(thus overwriting your content with a blank file)?

As shown in the below session, it works for me:

####################################
tchase at agix2:~/tmp$ python
Python 2.4.4 (#2, Apr  5 2007, 20:11:18)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more 
information.
 >>> f = open('test.txt', 'w')
 >>> f.writelines('hello\n')
 >>> f.writelines('world\n')
 >>> f.close()
 >>> import shutil
 >>> shutil.copyfile('test.txt', 'test2.txt')
 >>>
tchase at agix2:~/tmp$ cat test.txt
hello
world
tchase at agix2:~/tmp$ cat test2.txt
hello
world
#####################################

You may also want to use f.write() rather than f.writelines() 
which seems to be your usage.  f.writelines() is used for writing 
an iterable of strings.  Thus, it would be used something like 
this trivial example:

   f.writelines(['hello\n', 'world\n'])

To confuse matters, it happens to work in your example, because a 
string is an iterable that returns each character in that string 
as the result, so code like this

   f.writelines('hello\n')

is effectively doing something like this

   f.write('h')
   f.write('e')
   f.write('l')
   f.write('l')
   f.write('o')
   f.write('\n')

(unless writelines is optimized to smarten up the code here)

-tkc








More information about the Python-list mailing list