Home > Mobile >  How to print relative path in file
How to print relative path in file

Time:11-13

So, I am trying to output folder & file structure to a txt file, using the below code. But I want to get relative paths outputed instead of absolute paths.


import os

absolute_path = os.path.dirname(__file__)

with open("output.txt", "w", newline='') as a:
    for path, subdirs, files in os.walk(absolute_path):
       a.write(path   os.linesep) 
       for filename in files:
         a.write('\t%s\n' % filename) 

For now this gives me something like this

C:\Users\User\OneDrive\bla\bla
C:\Users\User\OneDrive\bla\bla\folder1
    file1.xxx
    file2.xxx
    file3.xxx
C:\Users\User\OneDrive\bla\bla\folder2
    test1.txt

but I want to show only relative paths to where the script ran, not more

.\bla
.\bla\folder1
    file1.xxx
    file2.xxx
    file3.xxx
.\bla\folder2
    test1.txt

I have fiddled around a bit, but not getting to the solution, nor finding it here (or maybe I am not searching for the correct thing)

Any help would be appreciated

CodePudding user response:

If you know the path to you current module, and you know the path of each file you find, and all your files will be in subdirectories of the current directory, you can calculate the relative path yourself.

Strings have the .replace(string_to_replace, replacement_value) method which will do this for you.

import os

absolute_path = os.path.dirname(__file__)

with open("output.txt", "w", newline='') as a:
    for path, subdirs, files in os.walk(absolute_path):
       a.write(path.replace(absolute_path, '.')   os.linesep) 
       for filename in files:
         a.write('\t%s\n' % filename) 

CodePudding user response:

Beauty of python is, it os.path module ready for this kind of problems. You can use os.path.relpath() function

import os

absolute_path = os.path.dirname(__file__)

with open("output.txt", "w", newline='') as a:
    for path, subdirs, files in os.walk(absolute_path):
        a.write('.\\'   os.path.relpath(path   os.linesep, start=absolute_path)) 
        for filename in files:
            a.write('\t%s\n' % filename) 

Here start parameter is used to current directory from where relative path should be resolved.

  • Related