Search code examples
pythonos.walk

How do I remove a part of a name that os.walk shows?


So I have a lot of directories and don't want to click each one to see what files are in there. So I made a short script which makes it easier for me. The only problem I have is that some file names are super long. Is there a way I can shorten the output of the names? Here's the code

path = 'G:/'
for root, dirs, files in os.walk(path):
                    for name in files:
                        print(os.path.join(root, name, '\n')

can I remove the last like 10 letters of the output?

btw sorry if I made this wrong its my first time posting here...


Solution

  • If you'd like to slice the output only if it's super long:

    maxLen = 85
    for name in files:
        pathname = os.path.join(root, name, '\n')
        if len(pathname) > maxLen:
            #Trims the string only if it's longer than maxLen
            pathname = pathname[:maxLen]+"..." #Trailing dots indicate that has been trimmed
        print(pathname)
    

    Or, as suggested by @Cory Kramer, you could just trim the string:

    print(os.path.join(root, name, '\n')[:-10]) #Removes the last 10 characters in every case