Python script error for copying . txt files

Asked

Viewed 465 times

1

I made the following script to study. The goal is to copy all files with the extension '.txt' from the 'teste1' folder to the 'teste2' folder'.

import shutil
import os

#Para garantir que o path é o caminho absoluto
e = os.path.abspath("/home/charanko/Desktop/teste1")
f = os.path.abspath("/home/charanko/Desktop/teste2")

#Para confirmar que o path é um caminho absoluto
print(os.path.isabs(e))
print(os.path.isabs(f))

source = os.listdir(e)
for files in source:
    if files.endswith(".txt"):
        shutil.copy(files,f)

The following error is obtained:

True
True
Traceback (most recent call last):
  File "/home/charanko/Desktop/selectiveCopy.py", line 15, in <module>
    shutil.copy(files,f)
  File "/usr/lib/python3.6/shutil.py", line 245, in copy
    copyfile(src, dst, follow_symlinks=follow_symlinks)
  File "/usr/lib/python3.6/shutil.py", line 120, in copyfile
    with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'fil.txt'

That mistake: FileNotFoundError: [Errno 2] No such file or directory: 'fil.txt' I saw people on other topics talking about something related to the absolute path. I thought I understood, but no. The other mistakes I couldn’t understand what it is.

  • it seems that there is a letter missing in the name, ñ would be file.txt instead of fil.txt?

  • @Eltonnunes, no, the name of the text file I actually left 'fil.txt'

  • really ñ idea, what I would do at that time was to go printing the os.listdir folder by folder, until arriving at the file and compare with the path passed by os.path.abspath, is not the most optimized way, but great chance to know where the problem is

1 answer

1


The problem is that you are not specifying the file path when copying. The shutil is trying to access the file fil.txt in the current directory, which does not exist. You can resolve this by specifying the directory, thus:

source = os.listdir(e)
for files in source:
    if files.endswith(".txt"):
        shutil.copy(os.path.join(e, files), f)
  • 1

    Exactly that, it worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.