I want to copy the source file to the destination folder.
In the destination folder, I am creating n number of folders (That may be nested of any depth) and I want to paste file1.pdf in any random folders inside the destination folder.
I have done the following code
import shutil
destination_folder = "path_to_the_destination_folder"
source_file = "path_to_source_file\file1.pdf"
destination_file = "f{destination_folder}\any_random_folder_from_n_nested_folders\file1.pdf"
new_file= shutil.copy(source_file, destination_file )
print(new_file)
FYI: "destination_folder\any_random_folders_from_n_nested_folders" This path is present, means it is getting created successfully , checked using os.path.isdir()
And facing this issue for some files, not for all files..
But it is giving me an error:
FileNotFoundError: [Errno 2] No such file or directory:
File "\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 420, in copy
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 265, in copyfile
with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:
FileNotFoundError: [Errno 2] No such file or directory
I believe, you have incorrectly specified destination folder, try this:
import shutil
destination_folder = "path_to_the_destination_folder"
source_file = "path_to_source_file\file1.pdf"
destination = f"{destination_folder}\any_random_folders_from_n_nested_folders\file1.pdf"
dest = shutil.copy(source_file, destination)
print(dest)
If this doesn't work, then check if all the directories exist and also check the permissions.
This is issue is resolved..
I just changed folder names which I was creating according to user input.
Previous folder names: f"Fld+{datetimestamp}"
Current folder names: f"Fld+{folder_counter}"
Related
I upload a file through the form, check it, and only after checking it I want to add it to my database.
form = BookForm(request.POST, request.FILES)
file = form.files
path = file.get('book_file').temporary_file_path()
in path - '/tmp/tmpbp4klqtw.upload.pdf'
But as soon as I want to transfer this file from the temporary storage to some other folder, I get the following error:
path = os.replace(path, settings.MEDIA_ROOT)
IsADirectoryError: [Errno 21] Is a directory: '/tmp/tmpbp4klqtw.upload.pdf' -> '/home/oem/bla/bla'
Can't understand why this file is not in reality? What can I do about it? Is it possible to set some special path for the "temporary file"?
UPD:
You should use path = os.replace(path, settings.MEDIA_ROOT + '/name-of-file.pdf') – Willem Van Onsem
os.replace(…) [python-doc] expects a filename as target if you specify a file as source, so you can move this to:
os.replace(path, f'{settings.MEDIA_ROOT}/name-of-file.pdf')
you can also make use of shutil.move(…) [python-doc] to specify the directory, this function will also return the filepath of the target file:
from shutil import move
target_file = move(path, settings.MEDIA_ROOT)
I am using jupyterhub and hosting the .ipynb file and hosted on server. I have usecase to upload a CSV from localdrive file and read the same for other dataframe tasks.
uploader = widgets.FileUpload(
accept='*.csv', # Accepted file extension e.g. '.txt', '.pdf', 'image/*', 'image/*,.pdf'
multiple=False # True to accept multiple files upload else False
)
display(uploader)
[input_file] = uploader.value
print(input_file)
pd.read_csv(input_file)
print(input_file) - is printing Test.csv which is CSV file name
I am able to print [input_file] but `pd.read_csv(input_file)' is throwing below error
FileNotFoundError: [Errno 2] No such file or directory: 'Test.csv'
Not sure were the CSV is uploaded, how can i read that data. Please help.
I don't have your exact ipywidgets version, but can you try this:
input_file = list(uploader.value.values())[0]
content = input_file['content']
content = io.StringIO(content.decode('utf-8'))
df = pd.read_csv(content)
a very simple code to create a directory:
ssh_path = f"{os.getenv('HOME')}/temp/.ssh"
print(ssh_path)
os.mkdir(ssh_path)
it prints the path of directory and ends up with error
FileNotFoundError: [Errno 2] No such file or directory: '/Users/myusername/temp/.ssh'
/Users/myusername/temp/.ssh
Use os.makedirs() to create the intermediate folders.
os.makedirs(ssh_path)
If you use Path from pathlib, you can do:
ssh_path = f"{os.getenv('HOME')}/temp/.ssh")
ssh = Path(ssh_path)
ssh.mkdir(parents=true)
So far I have the following:
source_folder = 'file_location'
for file in os.listdir(source_folder):
if file.startswith('stnet_'):
os.rename(file, file.replace('stnet_a_b', '%s_' % time.ctime(os.path.getctime(file)) + 'stnet_a_b'))
The issue with is is I keep getting FileNotFoundError: [WinError 2] The system cannot find the file specified 'stnet_a_b.raw'
Can someone point out what I'm doing wrong?
Thanks.
os.listdir can only get the filenames without directory, while os.rename, os.path.getctime needs full name with directory(if your current directory is not conincidently file_location then the file will not be found).
You can use os.path.join to get the full name. And if you are on Windows you must make sure filename doesn't contain special characters which your code contains.
dir = r'file_location'
# os.chdir(dir) # in case you don't want to use os.path.join
for filename in os.listdir(dir):
print(filename)
if filename.startswith('stnet_'):
src = os.path.join(dir, filename)
ctime_str = str(time.ctime(os.path.getctime(src)))
ctime_str = ctime_str.replace(':', '').replace(' ', '') # remove special characters
fn_new = filename.replace('stnet_a_b',
'{}_'.format(ctime_str + 'stnet_a_b'))
des = os.path.join(dir, fn_new)
print('src={}, des={}'.format(src, des))
os.rename(src, des)
please try above code.
This code was suppose tu sort my desktop , path =/Users/nicolas/Desktop/prova/
and it works properly if the destination folder doesnt exist and the program create it ,
else if there is already a folder with the same name it give an error when he tries to move the files and it says
complete output:
.DS_Store
nltks
png
Scherm.png
Schermata 2018-03-28 alle 11.07.13.png
DS_Store
nltks
png
png
Traceback (most recent call last):
File "/Users/nicolas/Desktop/tts/work in progress/sorting machine.py", line 16, in
shutil.move(path+names[x],path+currentexp)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 292, in move
raise Error, "Destination path '%s' already exists" % real_dst
shutil.Error: Destination path '/Users/nicolas/Desktop/prova/png/Scherm.png' already exists
iMac:w
but i ve not any file in it with the ds_store estension and the "nltk" is just a folder that shouldnt move .
program
import os
import shutil
path = "/Users/nicolas/Desktop/prova/"
names = os.listdir(path)
for x in range (0,len(names)):
print names[x]
for x in range (0,len(names)):
exp = names[x].split(".")
currentexp = exp[-1]
print (currentexp)
if os.path.exists(path+currentexp):
shutil.move(os.path.join(path, names[x]), os.path.join(path,currentexp))
else:
os.makedirs(path+currentexp)
shutil.move(os.path.join(path, names[x]), os.path.join(path,currentexp))
# if names[x] not in os.path.exists(path+currentexp):
# shutil.move(path+names[x],path+curentexp)
thanks for the help
from the documentation:
If the destination is an existing directory, then src is moved inside that directory. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics
To sum it up, if the image exists in the target dir, and both source & target dirs are on the same filesystem, shutil.move can use os.rename, and os.rename fails because you cannot rename an object with the name of an already existing one. You have to delete the target first.
Here's how I'd rewrite it:
target_dir = os.path.join(path,currentexp)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
try:
os.remove(os.path.join(target_dir, names[x]))
except OSError:
pass # cannot remove or doesn't exist, ignore
shutil.move(os.path.join(path, names[x]), target_dir)
this simpler code tries to delete the target file before performing shutil.move. Of course os.remove can fail, failure is trapped, then shutil.move fails because of another error, but that's beyond our scope