'How to copy file from one path to another if path exist only
I am searching over internet but not getting
if my source and destination path exist then only copy source file : abc.csv to destination path
import shutil
shutil.copyfile("/demo/abc.csv" "/dummy/")
If destination path does not exist it is creating I don't want it to happen
if both path exist then only copy abc.csv from one path to another path
Solution 1:[1]
My interpretation of this question is that the source is a file and the target is a directory and furthermore that the copy should only be attempted if the source exists (as a plain file) and the target exists (as a directory). If that's the case then:
import os
import shutil
def safe_copy(source_file, target_directory):
if os.path.isfile(source_file) and os.path.isdir(target_directory):
shutil.copyfile(source_file, os.path.join(target_directory, os.path.basename(source_file)))
Given a source file /home/test.txt and a target directory /foo then if /home/test.txt exists and /foo is an existing directory then the copy will take place (if permitted) resulting in /foo/test.txt either being created or overwritten
Solution 2:[2]
You can use os.path.isdir() to check if a directory exists.
destination_dir = ""
file_name = ""
if os.path.isdir(destination_dir):
try:
path = os.path.join(destination_dir, file_name)
shutil.copyfile("/demo/abc.csv", path)
except:
# handle error
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 | Albert Winestein |
| Solution 2 |
