Renaming Files in Subdirectories using file path - python-3.x

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

Related

I am not able to open the file in python even after going to the correct path

able to print the file name
file not found error when open command is executed.(filenotfounderror)
for r, d, f in os.walk(path):
for file in f:
print(file)
k=open(file,'r')
The variable files is a list of file names
for root, dirs, files in os.walk(path):
print(f)
By running that code, it will print a list of files, not including the directories.
If you want to open each file, use this:
for root, dirs, files in os.walk(path):
for file in files:
k=open(root+"\\"+file,'r')
This works because you need the whole file path, root is the file path before the file, putting them together will give you the whole path.
file is just a file name, not it's path.
You can't expect to open a file from nested directory just by it's name.
To get a full path (which begins with top) to a file or directory in
dirpath, do os.path.join(dirpath, name).
for r, d, f in os.walk(path):
for file in f:
file_path = os.path.join(r, file)
print(file_path)
k = open(file_path, 'r')
You can look up the documentation for more info https://docs.python.org/3/library/os.html#os.walk and don't forget to close the file or use context manager!

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)

Does the following program access a file in a subfolder of a folder?

using
import sys
folder = sys.argv[1]
for i in folder:
for file in i:
if file == "test.txt":
print (file)
would this access a file in the folder of a subfolder? For Example 1 main folder, with 20 subfolders, and each subfolder has 35 files. I want to pass the folder in commandline and access the first subfolder and the second file in it
Neither. This doesn't look at files or folders.
sys.argv[1] is just a string. i is the characters of that string. for file in i shouldn't work because you cannot iterate a character.
Maybe you want to glob or walk a directory instead?
Here's a short example using the os.walk method.
import os
import sys
input_path = sys.argv[1]
filters = ["test.txt"]
print(f"Searching input path '{input_path}' for matches in {filters}...")
for root, dirs, files in os.walk(input_path):
for file in files:
if file in filters:
print("Found a match!")
match_path = os.path.join(root, file)
print(f"The path is: {match_path}")
If the above file was named file_finder.py, and you wanted to search the directory my_folder, you would call python file_finder.py my_folder from the command line. Note that if my_folder is not in the same directory as file_finder.py, then you have to provide the full path.
No, this won't work, because folder will be a string, so you'll be iterating through the characters of the string. You could use the os module (e.g., the os.listdir() method). I don't know what exactly are you passing to the script, but probably it would be easiest by passing an absolute path. Look at some other methods in the module used for path manipulation.

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

Resources