简体   繁体   中英

Shutil.copy causes file data deletion

I am using shutil.copy to copy the content of one file to another. However it is causing my orignal files to be deleted with the error of "no data in file"

I first tried this

    import shutil
    shutil.copy('keywords.txt', 'keywordsfinal.txt')

Then was told the files need to be open and in a writable format

    import shutil
    ab = open("keywords.txt","w")
    abc = open("keywordsfinal.txt","w")
    shutil.copy('keywords.txt', 'keywordsfinal.txt')
    ab.close()
    abc.close()

However with both code, even if I have something in each .txt file, for instance test1, and test2, both files will return empty.

I had this working before and returned to my program about 6 months later to find this error. Any help appreciated.

Recently however the below error also started to appear, I have no idea what it is and if it is with any relevance to my code.

 Traceback (most recent call last):
   File "C:\Python33\lib\random.py", line 249, in choice
     i = self._randbelow(len(seq))
   File "C:\Python33\lib\random.py", line 225, in _randbelow
     r = getrandbits(k)          # 0 <= r < 2**k
 ValueError: number of bits must be greater than zero

 During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
   File "C:\Users\*******\Desktop\*******\*********Python\new\Final - Copy.py", line      84, in <module>
     a = random.choice(list(f)).strip() #.strip cleans the line \n problem
   File "C:\Python33\lib\random.py", line 251, in choice
     raise IndexError('Cannot choose from an empty sequence')
 IndexError: Cannot choose from an empty sequence

You need to close the file handle first, and then you can use shutil. If you don't close file handle before using copy(), shutil will only create destination file but it will stay empty.

The above code then should look like this:

import shutil
ab = open("keywords.txt","w")
abc = open("keywordsfinal.txt","w")
ab.close()
abc.close()
shutil.copy('keywords.txt', 'keywordsfinal.txt')
  1. You shouldn't be opening the files before shutil.copy() .
  2. For the second problem, it looks like list(f) is empty.

shutil.copy() accepts filenames (strings) as arguments. It opens files for you. You might have confused it with shutil.copyfileobj() that accept file objects. Even with copyfileobj() you shouldn't use "w" mode for the file you want to copy from (the first argument, the source).

"w" mode (stands for "write" ) means "open for writing, truncating the file first" (making the file empty).

#XXX REMOVE THIS CODE, IT DESTROYS THE FILES
ab = open("keywords.txt","w")
abc = open("keywordsfinal.txt","w")

Note: removing the offending lines from your code won't restore the files. Once they are empty; they keep being empty. You need to repopulate them. It should solve your second problem: calling random.choice() with an empty list:

>>> import random
>>> random.choice([])
Traceback (most recent call last):
  File "/usr/lib/python3.2/random.py", line 249, in choice
    i = self._randbelow(len(seq))
  File "/usr/lib/python3.2/random.py", line 225, in _randbelow
    r = getrandbits(k)          # 0 <= r < 2**k
ValueError: number of bits must be greater than zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.2/random.py", line 251, in choice
    raise IndexError('Cannot choose from an empty sequence')
IndexError: Cannot choose from an empty sequence

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM