os.listdir(path) and non-string as input - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: os.listdir(path) and non-string as input (/thread-12208.html) |
os.listdir(path) and non-string as input - metalray - Aug-14-2018 Dear Python Experts, I am trying to interate through folders in my root directory. With the start of the first interation (folder) a new folder should be created named existingname+'_flip'. I then want to look through the files of the original folder and copy them over to the new folder. The copy code is not realized yet, for now I want to get the loop right but I struggle. While I loop through "dirs" the following error comes: for file_path in os.listdir(path): TypeError: listdir: path should be string, bytes, os.PathLike or None, not tuple It seems, I got the input type to the function wrong. How can I convert "path" to string and is that really the right way? def main(): #interate through tub folders rootdir = 'C:/Users/xxx/Downloads/xxx/tubs_J/thinktank/' for dirs in os.walk(rootdir): #create new folder = existing name + _flip outPath = os.path.join(dirs, '_flip') if not os.path.exists(outPath): os.makedirs(outPath) path = dirs #iterate through the names of contents of the folder for file_path in os.listdir(path): print(file_path) #write file then save newpathwouldbe = os.path.join(outPath, file_path) if __name__ == '__main__': main() RE: os.listdir(path) and non-string as input - Gribouillis - Aug-14-2018 According to the documentation, os.walk generates 3-tuples (dirpath, dirnames, filenames) , so you need to writefor root, dirs, files in os.walk(rootdir): ...root is a directory, dirs is a list of names of subdirectories and files is a list of names of subfiles. With your present code, dirs is a 3-tuple. RE: os.listdir(path) and non-string as input - metalray - Aug-14-2018 Hi Gribouillis, Thank you so much for your input! I see, thanks for the hint. I thought I can just leave the other two out if I only want the "dir". OK. Now I am here: TypeError: listdir: path should be string, bytes, os.PathLike or None, not list Similar error. dirs is not a string. How can I convert it to a string? I tried os.listdir(str(path)) but I think I need the absolute path...I think RE: os.listdir(path) and non-string as input - metalray - Aug-14-2018 Why is outpath not concatenating properly? #interate through tub folders rootdir = 'C:/Users/xxx/data_thinktank/' for root, dirs, files in os.walk(rootdir): flip = r'_flip' outpath = os.path.join(str(dirs), flip) print(outpath) Output of print statement ['folder_1_xx']\_flip RE: os.listdir(path) and non-string as input - metalray - Aug-15-2018 OK, got it. outpath = os.path.join(rootdir, dir+"_flip") now I a at this: |