This question already has answers here:
Rename multiple files inside multiple folders
(3 answers)
Closed 4 years ago.
i'm trying to erase all indexes (characters) except the last 4 ones and the files' extension in python. for example:
a2b-0001.tif to 0001.tif
a3tcd-0002.tif to 0002.tif
as54d-0003.tif to 0003.tif
Lets say that folders "a", "b" and "c" which contains those tifs files are located in D:\photos
there many of those files in many folders in D:\photos
that's where i got so far:
import os
os.chdir('C:/photos')
for dirpath, dirnames, filenames in os.walk('C:/photos'):
os.rename (filenames, filenames[-8:])
why that' not working?
So long as you have Python 3.4+, pathlib makes it extremely simple to do:
import pathlib
def rename_files(path):
## Iterate through children of the given path
for child in path.iterdir():
## If the child is a file
if child.is_file():
## .stem is the filename (minus the extension)
## .suffix is the extension
name,ext = child.stem, child.suffix
## Rename file by taking only the last 4 digits of the name
child.rename(name[-4:]+ext)
directory = pathlib.Path(r"C:\photos").resolve()
## Iterate through your initial folder
for child in directory.iterdir():
## If the child is a folder
if child.is_dir():
## Rename all files within that folder
rename_files(child)
Just note that because you're truncating file names, there may be collisions which may result in files being overwritten (i.e.- files named 12345.jpg and 22345.jpg will both be renamed to 2345.jpg, with the second overwriting the first).
Related
This question already has answers here:
List only files in a directory?
(8 answers)
how to check if a file is a directory or regular file in python? [duplicate]
(4 answers)
Closed 2 months ago.
I have a directory and need to get all files in it, but not subdirectories.
I have found os.listdir(path) but that gets subdirectories as well.
My current temporary solution is to then filter the list to include only the things with '.' in the title (since files are expected to have extensions, .txt and such) but that is obviously not optimal.
We can create an empty list called my_files and iterate through the files in the directory. The for loop checks to see if the current iterated file is not a directory. If it is not a directory, it must be a file.
my_files = []
for i in os.listdir(path):
if not os.path.isdir(i):
my_files.append(i)
That being said, you can also check if it is a file instead of checking if it is not a directory, by using if os.path.isfile(i).
I find this approach is simpler than glob because you do not have to deal with any path joining.
This question already has answers here:
How to delete the contents of a folder?
(26 answers)
Closed 1 year ago.
I am trying to create a python script to help clean up a folder that I create with powershell. This is a directory that contains folders named after the users for them to put stuff into.
Once they leave our site, their folder remains and for all new staff who come a folder gets created. This means that we have over 250 folders but only 100 active staff. I have a test folder that I am using so that I can get the script working and then add in extra bits like moving the directories to an old location, and then deleting them based on age. But at the moment I am working on the delete portion of the script. So far I have the below script, it runs with no errors, but it doesn't actually do anything and I am failing to see why..
It should be reading a csv file that I have of all current staff members, and then comparing that to the folders located in the filepath and then removing any folders that dont match the names in the CSV file.
The CSV file is generated from powershell using the same script that I used to create them.
import os
import pandas as pd
path = "//servername/Vault/Users$"
flist = pd.read_csv('D:/Staff List.csv')
file_name = flist['fileName'].tolist()
for fileName in os.listdir(path):
#If file is not present in list
if fileName not in file_name:
#Get full path of file and remove it
full_file_path = os.path.join(path, fileName)
os.remove(full_file_path)
Use shutil and recursively remove all old user directories and their contents.
import shutil
PATH = 'D:/user/bin/old_dir_to_remove'
shutil.rmtree(PATH)
This question already has answers here:
How to do a recursive sub-folder search and return files in a list?
(13 answers)
Closed 2 years ago.
I have a big folder in which there are many subfolders. Each of those subfolders can also have some subfolders ( number can be different ) in it. This goes on for some levels. And in the end, there is a text file. How can I make a python program that traverses the entire directory as deep as it goes and prints the name of the text file? In simpler terms, I want to navigate through the directory as long as there are no more sub-directories?
Use os.walk.
For instance, creating a deep hierarchy like
$ mkdir -p a/b/c/d/e/f/g
$ touch a/b/c/d/e/f/g/h.txt
and running
import os
for dirname, dirnames, filenames in os.walk('.'):
for filename in filenames:
filepath = os.path.join(dirname, filename)
print(filepath)
yields
./a/b/c/d/e/f/g/h.txt
– do what you will with filepath.
Another option, if you're using Python 3.5 or newer (and you probably should be) is glob.glob() with a recursive pattern:
>>> print(glob.glob("./**/*.txt", recursive=True))
['./a/b/c/d/e/f/g/h.txt']
This question already has answers here:
Python error os.walk IOError
(2 answers)
Closed 4 years ago.
I am trying to create a list of paths for multiple files with the same name and format from different folders. I tried doing this with os.walk with the following code:
import os
list_raster = []
for (path, dirs, files) in os.walk(r"C:\Users\Douglas\Rasters\Testing folder"):
for file in files:
if "woody02.tif" in file:
list_raster.append(files)
print (list_raster)
However, this only gives me two things
the file name
All file names in each folder
I need the the full location of only the specified 'woody02.txt' in each folder.
What am I doing wrong here?
The full path name is the first item in the tuples in the list returned by os.walk, so it is assigned to your path variable already.
Change:
list_raster.append(files)
to:
list_raster.append(os.path.join(path, file))
In the example code you posted you are appending files to your list instead of just the current file, in order to get the full path and file name for the current file you would need to change your code to something like this:
import os
list_raster = []
for (path, dirs, files) in os.walk(r"C:\Users\Douglas\Rasters\Testing folder"):
for file in files:
if "woody02.tif" in file:
# path will hold the current directory path where os.walk
# is currently looking and file would be the matching
# woody02.tif
list_raster.append(os.path.join(path, file))
# wait until all files are found before printing the list
print(list_raster)
This question already has answers here:
Rename multiple files in a directory in Python
(15 answers)
Closed 4 years ago.
Looking to change the file extension from .txt to .csv
import os, shutil
for filename in os.listdir(directory):
# if the last four characters are “.txt” (ignoring case)
# (converting to lowercase will include files ending in “.TXT”, etc)
if filename.lower().endswidth(“.txt”):
# generate a new filename using everything before the “.txt”, plus “.csv”
newfilename = filename[:-4] + “.csv”
shutil.move(filename, newfilename)
You can use os and rename.
But let me give you a small advice. When you do these kind of operations as (copy, delete, move or rename) I'd suggest you first print the thing you are trying to achieve. This would normally be the startpath and endpath.
Consider this example below where the action os.rename() is commented out in favor of print():
import os
for f in os.listdir(directory):
if f.endswith('.txt'):
print(f, f[:-4]+'.csv')
#os.rename(f, f[:-4]+'.csv')
By doing this we could be certain things look ok. And if your directory is somewhere else than . You would probably need to do this:
import os
for f in os.listdir(directory):
if f.endswith('.txt'):
fullpath = os.path.join(directory,f)
print(fullpath, fullpath[:-4]+'.csv')
#os.rename(fullpath, fullpath[:-4]+'.csv')
The os.path.join() will make sure the directory path is added too.