Working with shutil and os: [Errno 2] No such file or directory 'folder' - python-3.x

import os, shutil
directory = 'C:\\Users\\MinJun\\Documents\\Python exercise solutions'
def move_files(_dir):
for file in os.listdir(_dir): #check every file in directory
if os.path.isdir(file): #if it is a folder, skip
continue
if file.endswith('.py'): #if file ends with .py, skip
continue
else: #move file to newfolder, (it will automatically create one)
shutil.move(file, directory.join('\\newfolder'))
move_files(directory)
Hello, I am trying to move files that are not folders or .py files to a folder that does not exist (but will be created with shutil.move). I get an error in the shutil module:
FileNotFoundError: [Errno 2] No such file or directory: 'graphics'
My folder 'graphics' is the first item in the directory.

Try
shutil.move(file, ''.join([directory, '\\newfolder'])
join does probably not work as you expected: https://docs.python.org/3.5/library/stdtypes.html#str.join
If you print(directory.join('\\newfolder')) you can see what it resulted in, and that this path for sure does not exist.
There is also os.path.join(path, *paths), which is sort of a "path-aware" string joining function.

Related

Renaming Files in Subdirectories using file path

Scenario: I am trying to Rename all .txt file named "a.txt" in all subfolders of a directory.
Question: I came up with the following code, but it has and issue: My loops don't work as expected, I was hoping to get the directory loop, to use the last part of the path, and use that string to rename the file. Right now, my code will rename the file with the latest directory name. How can this be fixed?
Code:
import os
import fnmatch
directory = "C:/Users/DGMS/Desktop/Test"
for root, subdirectories, files in os.walk(directory):
for subdirectory in subdirectories:
pathtest = os.path.basename(os.path.normpath(os.path.join(root, subdirectory)))
print(pathtest)
for file in files:
if fnmatch.fnmatch(file, 'a.txt'):
os.rename(os.path.join(root, file),(os.path.join(root, pathtest)))
print(os.path.join(root, file))
Here is a better code for what you want. All "a.txt" now becomes "b.txt"
import os
rootdir = 'C:/Users/sid/Desktop/test'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file == "a.txt"
os.rename(os.path.join(subdir, file),os.path.join(subdir, "b.txt"))

WinError2 keeps popping up with this python 3.7.3 script to delete files in a file tree without having to scroll through them

I am REALLY (2 days) new to all of this. I am trying to delete a bunch of files in a folder in my external HD with a python 3.7.3 script but an error keeps popping up.
Firstly, this code works fine and finds the folders:
import os
for folderName, subfolders, filenames in os.walk("D:\Practice"):
for filename in filenames:
if filename.endswith('practice.docx'):
#os.unlink(filename)
print(filename)
But then when I remove the print(filename) the remove the hash, the folders can't be deleted with the following error popping up:
import os
for folderName, subfolders, filenames in os.walk("D:\Practice"):
for filename in filenames:
if filename.endswith('practice.docx'):
os.unlink(filename)
os.unlink(filename) FileNotFoundError: [WinError 2] The system cannot find the file specified: 'rootpractice.docx'
The 'rootpractice' doc is clearly recognised but won't be deleted.
Does anyone know how I can solve this? Any help for this total beginner is much appreciated.
os.unlink and similar other methods which require file paths expect either a link relative to current folder in which your script is running (which you can find out with os.getcwd() ), or the full path.
When you are iterating with os.walk, you are only passing the filename and not the full path. Try this:
import os
for folderName, subfolders, filenames in os.walk("D:\Practice"):
for filename in filenames:
if filename.endswith('practice.docx'):
full_path = os.path.join(folderName, filename)
print("About to delete the file: {}".format(full_path))
os.unlink(full_path)

Can`t use the files inside my subdirectories

I`m creating a program that can read certain data from some txt files, the problem comes when I try to use the files inside subdirectories (the subdirectories are inside the main directory of the program. I'm using a for the option to find all the files and then create a new file with the info that I found. The main problem is that I can't read those files.
I tried using a for a function that creates a list of directories, files and roots, this works fine, but in the moment of running the file it says "it cannot be found txt file". The if not condition is made so the program excludes all.DS_Store files. I think the problem could be the way I open the file but im not sure
for root, directories, filenames in os.walk("Files_to_Insert"):
if not (filenames[-1] == ".DS_Store"):
lastFile = filenames[-1]
print lastFile
with open (lastFile, 'rt') as myfile:
IOError: [Errno 2] No such file or directory: txt
The mistake happens in the with open because it can`t find the file.
When I print I get all the txt files, but I can,t use them in the "with open"
A typical os.walk I use goes like this:
import os
for root, directories, filenames in os.walk("."):
for f in filenames:
if f.endswith(".DS_Store"):
continue
print(os.path.abspath(f))
with open (os.path.abspath(f), 'rt') as myfile:
I solve it by giving the path and the text file in separate strings:
for root, directories, filenames in os.walk("Files_to_Insert"):
if not(filenames[-1] == ".DS_Store"):
lastFile = filenames[-1]
# print (lastFile)
with open(str(root) + '/' + lastFile,'rt') as myfile:

I am getting FileNotFoundError: [Errno 2] No such file or directory: 'dna.txt' on Pycharm? Where do I put file to read?

I am trying to open 2 text files on PyCharm but it says file not found. Where do I put the files so they can be found?
I tried moving the files to the folder where all my PyCharm projects are kept but it didn't work.
dna = open('dna.txt', 'r')
dna.close()
dna_results = open("dnaresults.txt", "w")
dna_results.close()
Expected: I don't know honestly, for the text file to open on PyCharm so I can read it?
Actual: FileNotFoundError: [Errno 2] No such file or directory: 'dna.txt'
You need to pass the full path of the file in order to open it, for e.g. if the file is located at /home/john/dna.txt, you need to do.
dna = open('/home/john/dna.txt', 'r')
dna.close()
You can put your file anywhere you want, but you always need to pass the full path of the file in order to access it, otherwise the python interpreter doesn't know where to find it.
As an additional tidbit, if the dna.txt is located in the same folder as where the script is located, dna = open('dna.txt', 'r') will work

Move first file from folder to current directory

I need to move the first file of a folder to my current directory:
import os
import shutil
shutil.move(os.listdir('path to folder')[-1], os.getcwd())
I get the error:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'name of the file I want to move'
Could someone point out what I am doing wrong, please?
Thank you!
Well, when I've had to move files I wrote something like this:
for file in os.listdir(self.dlPth):
newfile = os.path.join(self.destPth, "name-of-new-file")
shutil.move(os.path.join(self.dlPth,file), newfile)
destPth is the destination path and dlPth is the one where my file was downloaded.
Can you give the paths you are using? I mean the exact way you are writing them in your code?
EDIT
dl = os.path.join(os.getenv('USERPROFILE'), 'Downloads')
shutil.move(os.path.join(dl, os.listdir(dl)[0]), (dl+"\\test\\"))
listdir[index] will only return a file name, not a path. That's why it can't find the wanted file

Resources