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

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)

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"))

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:

How to find and then open file with Python

I want to find a file and open it!
Right now I have some problems!
Basically, I don't know how to find the file, I know how to find a file in the same directory but not globally on the computer! Can anyone help me?
Hier is my code
import os
for root, dirs, files in os.walk(".txt"):
for filename in files:
os.startfile(filename)
Reading the fine documentation would be a good place to start.
"Globally on the computer" means / slash.
Start there, or perhaps in your home directory.
import os
for root, dirs, files in os.walk('/'):
for file in files:
if file.endswith('.txt'):
filename = os.path.join(root, file)
os.startfile(filename)
You can try my answer at:
https://stackoverflow.com/questions/2212643/python-recursive-folder-read/55193831#55193831
code:
import glob
import os
root_dir = <root_dir_here>
for filename in glob.iglob(root_dir + '**/**', recursive=True):
if os.path.isfile(filename):
with open(filename,'r') as file:
print(file.read())

Python: "FileNotFoundError" Despite being able to print such files

I'm working on a Python3 script where the code walks through directories and sub-directories to pull out all gzipped warc files.
I'd like to also add that the files are not in my home directory
file_path = os.path.join('/nappa7/pip73/Service')
walk_file(parallel_bulk, file_path)
Perhaps python is not looking where i think it's looking, nevertheless, here is my walk_file functions:
def walk_file(bulk, file_path):
warc = warcat.model.WARC()
try:
for (file_path,dirs,files) in os.walk(file_path):
for filenames in files:
if filenames.endswith('.warc.gz'):
warc.load(filenames)
except ValueError:
pass
When I replace the warc.load(filenames) with a print statement like so:
if filenames.endswith('.warc.gz'):
print(filenames)
The filenames are printed out onto the console as expected. Therefore, It leads me to believe that python was able to succesfully locate all warc.gz files. However, when i try the warc.load(filenames), i get:
FileNotFoundError: [Errno 2] No such file or directory: 'Sample.warc.gz'
I can certainly use some guidance.
Thank you.
So for anyone else who has a similar issue:
changing the code to this worked:
warc.load(os.path.join(file_path, filenames))
You need to use os.path.join(file_path, filenames) instead of just filenames.
Otherwise the operating system will look for the file in the current directory instead of file_path.
(And why is filenames plural when it refers to a single filename?)

Python 3.5:Not able to remove non alpha -numeric characters from file_name

i have written a python script to rename all the files present in a folder by removing all the numbers from the file name but this doesn't work .
Note :Same code works fine for python2.7
import os
def rename_files():
#(1) get file names from a folder
file_list = os.listdir(r"D:\prank")
print(file_list)
saved_path = os.getcwd()
print("Current working Directory is " + saved_path)
os.chdir(r"D:\prank")
#(2) for each file ,rename filename
for file_name in file_list:
os.rename(file_name, file_name.translate(None,"0123456789"))
rename_files()
Can anyone tell me how to make it work.Is the translate function which is not working properly
The problem is with os.rename() portion of your code.
os.rename() requires you to give it a full path to the file/folder you want to change it to, while you only gave it the file_name and not the full path.
You have to add the full path to the folders/files directory.
so it should look like this:
def rename_files():
# add the folder path
folder_path = "D:\prank\\"
file_list = os.listdir(r"D:\prank")
print(file_list)
saved_path = os.getcwd()
print("Current working Directory is " + saved_path)
os.chdir(r"D:\prank")
# Concat the folder_path with file_name to create the full path.
for file_name in file_list:
full_path = folder_path + file_name
print (full_path) # See the full path here.
os.rename(full_path, full_path.translate(None, "0123456789"))
look up the documentation for os, heres what ive found on rename:
os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
Rename the file or directory src to dst. If dst is a directory, OSError will be raised. On Unix, if dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if dst already exists, OSError will be raised even if it is a file.
This function can support specifying src_dir_fd and/or dst_dir_fd to supply paths relative to directory descriptors.
If you want cross-platform overwriting of the destination, use replace().
New in version 3.3: The src_dir_fd and dst_dir_fd arguments.
heres a link to the documentation, hope this helps, thanks
https://docs.python.org/3/library/os.html
Others have pointed out other issues with your code, but as to your use of translate, in Python 3.x, you need to pass a dictionary mapping ordinals to new values (or None). This code would work:
import string
...
file_name.translate(dict(ord(c), None for c in string.digits))
but this seems easier to understand:
import re
...
re.sub(r'\d', '', file_name)

Resources