Try this. In such cases I prefer to write an auxiliary function rather than repeatedly type (almost) the same long line (too error-prone). Likewise, if the list comprehension gets too long, I prefer the loop form.
import os
def files(path):
result = []
for name in os.listdir(path):
fullname = os.path.join(path, name)
if os.path.isfile(fullname):
result.append(name)
return result
path = r"C:\Users\DELL PC\Desktop\Msc Project\MSc project\dataset"
for file in os.listdir(path):
print(file)
lowfiles = files(os.path.join(path, r"Training data\LOW"))
highfiles = files(os.path.join(path, r"Training data\HIGH"))
To clarify the comment below: the following will enter an infinite loop that prints 1, 2, 3, 1, 2, 3, 1, 2, 3...
a = [1, 2, 3]
for i in a:
a.append(i)
print(i)
Never add elements to a container on which you are doing a loop.
Here you are trying to do this:
for i in lowfiles:
lowfiles.append([i, 'Low'])
So if lowfiles
initially contains ["file1", "file2"]
, then after the first loop it will be ["file1", "file2", ["file1", "Low"]]
, then ["file1", "file2", ["file1", "Low"], ["file2", "Low"], [["file1", "Low"], "Low"], ...]
. You don't want to do that.
I am only guessing, but it you want to rename your files by appending "Low" at the end of the name, then:
First modify the function files
above to append the fullname
(with directory) rather than only the name
without the directory), so that you don't have to os.path.join
again and again.
To rename files do the following:
for fullname in files(os.path.join(path, r"Training data\LOW")):
os.rename(fullname, fullname + "Low")
If there is a file extension you don't want to change, you can do this:
for fullname in files(os.path.join(path, r"Training data\LOW")):
base, ext = fullname.rsplit(".", 1)
os.rename(fullname, base + "Low." + ext)
And if you don't want to renames files, you will have to clarify what you are trying to do.