For some reason whenever I use os.rmdir or os.removedirs and os.makedirs or os.mkdir
it doesn't work. My code is
import os
path = r"C:\Users\User\Desktop\Test\New Text Document.txt"
os.rmdir(path)
and the output is
Traceback (most recent call last):
File "C:\Users\User\Desktop\Python\projects\projects in python files\security\main.py", line 5, in <module>
os.rmdir(path)
NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\\Users\\User\\Desktop\\Test\\New Text Document.txt'
My computer has only one \
import os
path = r"C:\Users\User\Desktop\Test\New Text Document.txt"
os.remove(path)
Use os.remove(path)
os.rmdir(path) is used to delete an empty directory not a file
Related
So I have a really big folder from a dataset downloaded online that has almost 5500 folder each containing 6 or so images. Some of those images have cloth_front_mask in them.
Since there are way to many folder for me to go through each one of them and try to move the files to another directory, I tried creating a small script that would do that task for me but when I tried it I get a
Traceback (most recent call last):
File "C:\Users\Adam\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 557, in move
os.rename(src, real_dst)
FileNotFoundError: [WinError 2] The system cannot find the file specified: '10K21D003-C11#2=cloth_front_mask.jpg' -> 'C:\\Users\\Adam\\Downloads\\LIP_MPV_256_192\\MPV_256_192\\all\\all\\images\\cloth_mask\\10K21D003\\10K21D003-C11#2=cloth_front_mask.jpg'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#52>", line 9, in <module>
shutil.move(name, path, copy_function=shutil.copytree)
File "C:\Users\Adam\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 571, in move
copy_function(src, real_dst)
File "C:\Users\Adam\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 309, in copytree
names = os.listdir(src)
FileNotFoundError: [WinError 3] The system cannot find the path specified: '10K21D003-C11#2=cloth_front_mask.jpg'
Here's my code:
for root, dirs, files in os.walk('.'):
for name in files:
if 'mask' in name:
path = os.path.join('C:\\Users\\Adam\\Downloads\\LIP_MPV_256_192\\MPV_256_192\\all\\all\\images\\cloth_mask', name[:9])
if os.path.exists(path):
pass
else:
os.mkdir(path)
shutil.move(name, path, copy_function=shutil.copytree)
I got it. The problem was that in the shutil.move line I didn't specify the file's original folder. When I did so, it worked fine.
I know there are questions like that but I still wanted to ask this because I couldn't solve, so there is my code:
#! python3
import os
my_path = 'E:\\Movies'
for folder in os.listdir(my_path):
size = os.path.getsize(folder)
print(f'size of the {folder} is: {size} ')
And I got this error:
Traceback (most recent call last):
File "c:/Users/ataba/OneDrive/Masaüstü/Programming/python/findingfiles.py", line 7, in <module>
size = os.path.getsize(folder)
File "C:\Program Files\Python37\lib\genericpath.py", line 50, in getsize
return os.stat(filename).st_size
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'FordvFerrari1080p'
When I write print(folder) instead of getting their size it shows the folders so I don't think the program can't find them.
The problem may be that you are passing as an argument to os.path.getsize() just the folder name instead of the whole path to the folder
It may be that you have the file name as 'FordvFerrari1080p' rather than 'FordvFerrari1080p.mp4' (or whatever file type it may be)
I'm trying to rename a set of files using the following code. The File is within the folder but it gives the following error. My code is attached here with:
import os
path='absolute_path'
arr = os.listdir(path)
for i in arr:
old_name=i
old_name_part=old_name.split(".")
new_name=old_name_part[0]+".png"
print(i,'\t',old_name,'\t',new_name)
os.rename(i,new_name)
Error :
drone_0002_01320.jpg drone_0002_01320.jpg drone_0002_01320.png
Traceback (most recent call last):
File "/absolute_path/rename.py", line 23, in <module>
os.rename(i,new_name)
FileNotFoundError: [Errno 2] No such file or directory: 'drone_0002_01320.jpg' -> 'drone_0002_01320.png'
os.rename(i,new_name) takes the full path of your file
you can change it into this:
os.rename(os.path.join(path, i),os.path.join(path, new_name))
Consider read about pathlib module, it has some good function for those kind of problems
I am trying to loop over a Python directory, and I have a specific file that happens to be the last file in the directory such that I get an IOerror for that specific file.
The error I get is:
IOError: [Errno 2] No such file or directory: 'nod_gyro_instance_11_P_4.csv'
My script:
for filename in os.listdir("/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro"):
data = []
if filename.endswith(".csv"):
data.append(k_fold(filename))
continue
else:
continue
k_fold does this:
def k_fold(myfile, myseed=11109, k=20):
# Load data
data = open(myfile).readlines()
The entire traceback:
Traceback (most recent call last):
File "/Users/my_name/PycharmProjects/MY_Project/Cross_validation.py", line 30, in <module>
data.append(k_fold(filename))
File "/Users/my_name/PycharmProjects/My_Project/Cross_validation.py", line 8, in k_fold
data = open(myfile).readlines()
IOError: [Errno 2] No such file or directory: 'nod_gyro_instance_11_P_4.csv'
My CSV files are such:
nod_gyro_instance_0_P_4.csv
nod_gyro_instance_0_P_3.csv
nod_gyro_instance_0_P_2.csv
nod_gyro_instance_0_P_5.csv
...
nod_gyro_instance_11_P_4.csv
nod_gyro_instance_10_P_6.csv
nod_gyro_instance_10_P_5.csv
nod_gyro_instance_10_P_4.csv
Why doesn't it recognize my nod_gyro_instance_10_P_4.csv file?
os.listdir returns just filenames, not absolute paths. If you're not currently in that same directory, trying to read the file will fail.
You need to join the dirname onto the filename returned:
data_dir = "/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro"
for filename in os.listdir(data_dir):
k_fold(os.path.join(data_dir, filename))
Alternatively, you could use glob to do both the listing (with full paths) and extension filtering:
import glob
for filename in glob.glob("/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro/*.csv"):
k_fold(filename)
I have a folder with a few files that I would like to copy one directory up (this folder also has some files that I don't want to copy). I know there is the os.chdir("..") command to move me to the directory. However, I'm not sure how to copy those files I need into this directory. Any help would be greatly appreciated.
UPDATE:
This is what I have now:
from shutil import copytree, ignore_patterns
copytree("/Users/aaron/Desktop/test/", "/Users/aaron/Desktop/", ignore=ignore_patterns('*.py', '*.txt'))
I am getting the following error:
Traceback (most recent call last):
File "update.py", line 61, in <module>
copytree("/Users/aaron/Desktop/test/", "/Users/aaron/Desktop/", ignore=ignore_patterns('*.py', '*.txt'))
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/shutil.py", line 146, in copytree
os.makedirs(dst)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/os.py", line 157, in makedirs
mkdir(name, mode)
OSError: [Errno 17] File exists: '/Users/aaron/Desktop/'
The shutil module can do this, specifically the copyfile, copy, copy2 and copytree functions. http://docs.python.org/library/shutil.html
You probably want something along these lines:
import os
import shutil
fileList = os.listdir('path/to/source_dir')
fileList = ['path/to/source_dir/'+filename for filename in fileList]
for f in fileList:
shutil.copy2(f, 'path/to/dest_dir/')
You can of course filter some file names out during the call to os.listdir(). For example,
fileList = [filename for filename in os.listdir('path/to/source_dir') if filename[-3] is '.txt']
instead of fileList = os.listdir('path/to/source_dir') to get just the .txt files