5

I am very new to Python. I would like to work on an existing file (exist_file) and, in addition, to create a copy of it. The problem is, when I create the copy of the file, the exist_file becomes empty.

exist_file = open('some_pass/my_file.txt', 'r')
print exist_file.read() # Here the file is successfully printed
copy_of_file = open('new_copied_file.txt', 'w')
copy_of_file.write(exist_file.read())
print exist_file.read() # Here the file is empty

Why exist_file is empty?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Halona
  • 1,475
  • 1
  • 15
  • 26
  • You are opening the file with write flag `w` - `copy_of_file = open('new_copied_file.txt', 'w')` .... If you want to keep the current data... then open the file with append flag `a`-> `copy_of_file = open('new_copied_file.txt', 'a')` – sarveshseri Feb 04 '15 at 11:52
  • Try removing the line where you print out the file and you should find that it works as expected. You can only read the file once without resetting the file position. – Tim B Feb 04 '15 at 11:53
  • Related: [Iterating on a file doesn't work the second time](/q/10255273/4518341) – wjandrea Jan 22 '22 at 22:31

3 Answers3

7

As shown in this example in the Python documentation, when you call read() twice on a file without calling a .seek(0), the second call returns an empty string.

The best way to fix this is to keep the result of the first call in a variable.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Phylogenesis
  • 7,775
  • 19
  • 27
  • 2
    Also, make sure to close the file after writing to it (or use a [`with` statement](http://docs.python.org/2/reference/compound_stmts.html#the-with-statement)), otherwise it might take a while before Python decides to close it for you. – Tim Pietzcker Feb 04 '15 at 11:59
2

When you call read on a file object, you also move the file pointer to the end, hence your next calls to read return empty.

Two ways to resolve this:

  1. Store whatever is read into a buffer and use it henceforth

    exist_file = open('some_pass/my_file.txt', 'r')
    buffer = exist_file.read()
    print buffer  # Here the file is successfully printed
    copy_of_file = open('new_copied_file.txt', 'w')
    copy_of_file.write(buffer)
    print buffer # Here the file is successfully printed
    
  2. Use the read operation directly in write method. Remove all prior reads. Remove later reads too since they'll be empty.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Barun Sharma
  • 1,452
  • 2
  • 15
  • 20
1

Try the shutil module:

copyfile(src, dst)
Jonathan Davies
  • 882
  • 3
  • 12
  • 27