What should the counter count? The amount of matching/renamed files or the amount of all files?
Try not to use os.path.*
The module pathlib gives a nice high-level abstraction of Paths.
If you use it right, your code could also work on different operating systems with different directory structure.
For example Windows Users home is in: C:\Users
For linux it's in /home
The class method
pathlib.Path.home()
returns a
Path
object, which points to your current home directory independent of your OS that you're using. On Windows, you get back a
WindowsPath
which points to C:\Users\username and on Linux you get a
PosixPath
which points to /home/username. Mac should be the same as Linux.
You can do this also with os.path, but this is very low level.
from pathlib import Path
for source_file in Path.home().joinpath("Dokumente").glob("*.xlsx"):
# in my case the user is andre
# resulting Path:
# /home/andre/Deokumente
# the method glob will yield files and directories
# which matches the pattern *.xlsx
# glob only searches one level deep
# rglob searchs recursive
# iterdir does not pattern matching and just yields
# the paths (files and other) in the directory
# process only files, keep in mind, that you can
# also have a directory names like something.xlsx
if source_file.is_file():
print("OLD:", source_file)
# the attribute name of a Path object is a str
# creating a new name with replace
new_name = source_file.name.replace("XX", "05")
# now we need the full path to the target file
# the method with_name replaces the last part of
# a Path object
target_file = source_file.with_name(new_name)
print("NEW:", target_file)
# Path objects can also: rename, unlink, chmod, stat, open, read_text, ...
# to rename them:
# source_file.rename(source_file)
If the counter is needed, you can use enumerate to count all matching files:
path_iterator = Path.home().joinpath("Dokumente").glob("*.xlsx")
for file_count, source_file in enumerate(path_iterator, start=1):
...
Then you can use file_count in the for-loop if required and even after the for-loop has been finished, the file_count and source_file do have the last elements.
They are not removed.
Example:
for number in range(10):
pass # doing nothing
# -> 9, the last value of the for-loop
print(number)