I want to get a random file from a folder and copy it to another folder;
So, I get the files in the folder
root_src = 'D:\Downloads'
files = os.listdir(root_src)
file = random.choice(files)
new_root = os.path.join(root_src, 'new')
copyfile(file, new_path)
I get the following error:
FileNotFoundError: [Errno 2] No such file or directory: 'file-12.jpg'
So, I guess when I do random.choice I don't get the path
When you call os.listdir, it returns a list of the names of files in the folder.
It does not join those file names to the directory path (something of a consequence of the design choice of having strings masquerade as paths without any explicit Path object a la Java).
Wherever it is this problem emerges, you need to join them. To do this, from os import path and invoke path.join(root_src, file).
Note that if you use path as a variable name, you shouldn't do this. Rather, import os and invoke os.path.join(root_src, file).
Use below code
import os
root_src = 'D:\Downloads'
files = os.listdir(root_src)
file = random.choice(files)
new_root = os.path.join(root_src, 'new')
copyfile(os.path.join(root_src, file), new_path)
Related
I want to move all the files from multiple subdirectories to another folder in the same directory as the parent folder but get the following error:
FileNotFoundError: [Errno 2] No such file or directory: '/content/drive/MyDrive/Dev/FaceRec/lfw/Emmit_Smith/Emmit_Smith_0001.jpg' -> '/content/drive/MyDrive/Dev/FaceRec/negatives/Emmit_Smith_0001.jpg'
this is my code:
for directory in os.listdir('/content/drive/MyDrive/Dev/FaceRec/lfw'):
for file in os.listdir(os.path.join('/content/drive/MyDrive/Dev/FaceRec/lfw', directory)):
path = os.path.join('/content/drive/MyDrive/Dev/FaceRec/lfw', directory, file)
new_path = os.path.join('/content/drive/MyDrive/Dev/FaceRec/negatives', file)
os.replace(path, new_path)
Thank you for the help in advance
Try the following:
import os
import glob
import shutil
src_path = '/content/drive/MyDrive/Dev/FaceRec/lfw'
dest_path = src_path.replace('lfw', 'negatives')
flist = glob.glob(os.path.join(src_path, '*/*'))
for fname in flist:
shutil.move(fname, fname.replace(os.path.dirname(fname), dest_path))
Why this is better:
The glob functions helps to avoid one for loop and also prevents from repeatedly joining the paths together
shutil.movecreates the destination directory for you if it does not exist. Also it can handle symlinks.
By putting the paths in variables we can minimize copy past errors
I wanted to create a new txt file inside each directory each loop.
import os
path='/home/linux/Desktop'
os.chdir(path)
for i in range(10):
NewDir = 'File' + str(i)
os.makedirs(NewDir)
how can I put txt file in each created directory? thankyou
The typical way to create a new file is the following:
open(filepath, 'a').close()
The append ('a') mode will note overwrite existing files and create a new empty file if none exist. If you want to overwrite existing files, you can use the 'w' mode.
You can use pathlib to simplify file/directory manipulations.
from pathlib import Path
path = Path('/home/linux/Desktop')
for i in range(10):
new_dir = path / f'File{i}'
new_dir.mkdir()
(new_dir / 'some.txt').write_text('Some desired content')
The file creation is handled at opening. In your for loop, just add this:
open(NewDir + "/your_file_name.txt", 'w').close()
EDIT: added "/" to file name
If you are using os.mkdir it is going to create a new folder named as File0...,File9. You can try this to create file:
import os
path='/home/linux/Desktop'
os.chdir(path)
for i in range(10):
open(f"File{i}.txt","w").close()
This is going to create files under /home/linux/Desktop named as File0,File1,.....,File9.
I am trying to open the file from folder and read it but it's not locating it. I am using Python3
Here is my code:
import os
import glob
prefix_path = "C:/Users/mpotd/Documents/GitHub/Python-Sample-
codes/Mayur_Python_code/Question/wx_data/"
target_path = open('MissingPrcpData.txt', 'w')
file_array = [os.path.abspath(f) for f in os.listdir(prefix_path) if
f.endswith('.txt')]
file_array.sort() # file is sorted list
for f_obj in range(len(file_array)):
file = os.path.abspath(file_array[f_obj])
join_file = os.path.join(prefix_path, file) #whole file path
for filename in file_array:
log = open(filename, 'r')#<---- Error is here
Error: FileNotFoundError: [Errno 2] No such file or directory: 'USC00110072.txt'
You are not giving the full path to a file to the open(), just its name - a relative path.
Non-absolute paths specify locations in relation to current working directory (CWD, see os.getcwd).
You would have to either os.path.join() correct directory path to it, or os.chdir() to the directory that the files reside in.
Also, remember that os.path.abspath() can't deduce the full path to a file just by it's name. It will only prefix its input with the path of the current working directory, if the given path is relative.
Looks like you are forgetting to modify the the file_array list. To fix this, change the first loop to this:
file_array = [os.path.join(prefix_path, name) for name in file_array]
Let me reiterate.
This line in your code:
file_array = [os.path.abspath(f) for f in os.listdir(prefix_path) if f.endswith('.txt')]
is wrong. It will not give you a list with correct absolute paths. What you should've done is:
import os
import glob
prefix_path = ("C:/Users/mpotd/Documents/GitHub/Python-Sample-"
"codes/Mayur_Python_code/Question/wx_data/")
target_path = open('MissingPrcpData.txt', 'w')
file_array = [f for f in os.listdir(prefix_path) if f.endswith('.txt')]
file_array.sort() # file is sorted list
file_array = [os.path.join(prefix_path, name) for name in file_array]
for filename in file_array:
log = open(filename, 'r')
You are using relative path where you should be using an absolute one. It's a good idea to use os.path to work with file paths. Easy fix for your code is:
prefix = os.path.abspath(prefix_path)
file_list = [os.path.join(prefix, f) for f in os.listdir(prefix) if f.endswith('.txt')]
Note that there are some other issues with your code:
In python you can do for thing in things. You did for thing in range(len(things)) it's much less readable and unnecessary.
You should use context managers when you open a file. Read more here.
I have written a script. It finds the current path and changes the path and zips. Then I want that it just find the zip file copy it to another directory and at the end removes the content of the folder. But it zips once and zips again the whole folders and zip-file. The intial situation is as in Figure 1.
The script is like this:
import os
import zipfile
import shutil
import glob
Pfad = os.getcwd()
newPfad = 'D'+ Pfad[1:]
Zip_name=os.path.basename(os.path.normpath(Pfad))
shutil.make_archive(Zip_name, 'zip', Pfad)
if not os.path.exists(newPfad):
os.makedirs(newPfad)
dest_dir=newPfad
files = glob.iglob(os.path.join(Pfad, "*.zip"))
for file in files:
if os.path.isfile(file):
shutil.copy2(file, dest_dir)
shutil.rmtree(Pfad)
And finally the result is illustrated in the following figure.
The batch file is just for running the python script.
How can I get the following desired situation?
The issue is that zip file is created prior to listing the directory contents, therefore empty zip file is added to. Create archive in the parent directory and then move it. Moving a file or directory is cheap and atomic.
import os
import shutil
cwd = os.path.abspath(os.path.curdir)
zip_target = os.path.join(cwd, os.path.basename(cwd)) + '.zip'
zip_source = shutil.make_archive(cwd, 'zip')
os.rename(zip_source, zip_target)
I'm trying to build a little renaming program to help save me time in the future.
Basically it will go through directories I point it too and rename files if they meet certain criteria.
I have written what I need but I have a bug in the very beginning that I can't figure out.
Here is the code:
import os
import fnmatch
for file in os.listdir("""/Users/Desktop/TESTME"""):
if fnmatch.fnmatch(file,'MISC*'):
os.rename(file, file[4:12] + '-13-Misc.jpg')
When I try to run it I am getting this:
Traceback (most recent call last):
File "/Users/Documents/Try.py", line 6, in <module>
os.rename(file, file[4:12] + '-13-Misc.jpg')
OSError: [Errno 2] No such file or directory
I also tried this:
if fnmatch.fnmatch(file,'MISC*'):
fun = file[4:12] + '-13-Misc.jpg'
os.rename(file, fun)
But I get the same thing.
It's not recognizing the file as a file.
Am I going about this the wrong way?
You'll need to include the full path to the filenames you are trying to rename:
import os
import fnmatch
directory = "/Users/Desktop/TESTME"
for file in os.listdir(directory):
if fnmatch.fnmatch(file, 'MISC*'):
path = os.path.join(directory, file)
target = os.path.join(directory, file[4:12] + '-13-Misc.jpg'
os.rename(path, target)
The os.path.join function intelligently joins path elements into a whole, using the correct directory separator for your platform.
The function os.listdir() only returns the file names of the files in the given directory, not their full paths. You can use os.path.join(directory, file_name) to reconstruct the full path of the file.
You could also do this in bash:
cd /Users/Desktop/TESTME/
for f in MISC*; do mv "$f" "${f:4:8}-13-Misc.jpg"; done