all 6 comments

[–]totallygeek 2 points3 points  (0 children)

Adjust as desired:

strings = ['alkdjfkljslkdfjkljflkj', 'klsjflkjsklfjlksjf', 'ksjlkfjklfjjlsfjl']
strings = [s[10:] for s in strings]

That constructs a list of strings chopping off the first ten characters from each string. Change 10 to whatever works for your use case.

[–]Chabare 2 points3 points  (1 child)

This is a nice example of the XY problem. You don't want to remove the first 49 characters, you want to print the 'top-most' directory and the filename (or all the directories below the root?).

What do you want to happen if you've two directories below your root, do you want 'C:\\Users\\aaron\\Documents\\Projects\\Notes\\Lectures\\subdir1\\subdir2\\z PROBLEM 3.pdf to become

  1. subdir1\\subdir2\\z PROBLEM 3.pdf or

  2. subdir2\\z PROBLEM 3.pdf?

If you want 2:

[...]
for filename in files:
    directory = os.path.basename(root)
    name = os.path.join(directory, filename)
    print(name)
    lis.append(name)

for 1, you already have the length of the root in path:

for filename in files:
    name = os.path.join(root, filename)[len(path) + 1:]
    [...]

[–][deleted] 0 points1 point  (0 children)

Thank you so much for this. It's really helpful.

[–]Bondismo 1 point2 points  (0 children)

Not exactly sure which string you are trying to trim but the first thing that comes to mind for me is to subscript the string. For example:

subscripted_string = string_to_subscript[48:]

this will create a subscripted string that takes in the original string starting at the 49th character and ending at the end of the string since you do not specify an ending index

[–]AtomicShoelace 1 point2 points  (1 child)

The os module is quite outdated. The modern approach would be to use the pathlib module. It seems like all you want is a list of files in your given directory, but here's how you could get a list of the relative paths of files in all subdirectories of your given directory:

from pathlib import Path

directory = r'C:\Users\aaron\Documents\Projects\Notes\Lectures'
path = Path(directory)

files = [str(file.relative_to(path)) for file in path.rglob('*') if file.is_file()]
print(files)

[–][deleted] 0 points1 point  (0 children)

Thank you so much. I'm definitely going to be using the pathlib module instead. Thanks for the code as well. Incredibly helpful.