'how to copy files with extension .txt?
I am trying create a program to automatizate the creation of the files .txt of directory to my work in python. I managed to create a code to find all the files with extension .txt . but but i can't copy all these files to another folder, because it shows me the following error. I leave you my code, so that you can help me regarding the error that it shows me.
import pathlib
from datetime import date
from shutil import copyfile
date_backup = date.today()
str_date_backup = str(date_backup).replace('-','.')
path_input = r'D:\2 PERSONAL'
ruta = pathlib.Path(path_input)
for archivo in ruta.glob("**\\*.txt"):
path_out = r'D:\Backup' + '\\' + str_date_backup + " - " + archivo
copyfile(path_input, path_out)
The ERROR is:
Traceback (most recent call last):
File "D:\5 PROYECTOS PYTHON\Automatizar_Backup\Automatizar_Backup.py", line 24, in <module>
path_out = r'D:\Backup' + '\\' + str_date_backup + " - " + archivo
TypeError: can only concatenate str (not "WindowsPath") to str
Solution 1:[1]
This happens because using glob on a pathlib.Path object yields all the files that match the pattern (in your case, "**\*.txt"). Luckily, this is as easy as converting your WindowsPath (or PosixPath in other systems) to string:
for file in pathlib.Path(".").glob("*.txt"):
file = str(file)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | aaossa |
