AndrewD AndrewD - 11 months ago 51
Linux Question

Python: Trying to put the contents of a folder into a text file:

I'm in the process of writing a python script that takes two arguments that will allow me to output the contents of a folder to a text file for me to use for another process. The snippet of I have is below:


import cv2
import numpy as np
import random
import sys
import os
import fileinput


img_path= str(sys.argv[1])
file_path = str(sys.argv[2])

print img_path
print file_path

cmd = 'find ' + img_path + '/*.png | sed -e "s/^/\"/g;s/$/\"/g" >' + file_path + '/desc.txt'

print "command: ", cmd

#Generate desc.txt file:

When I try and run that from my command line, I get the following output, and I have no idea how to fix it.

sh: 1: s/$//g: not found

I tested the command I am using by running the following command in a fresh terminal instance, and it works out fine:

images/*.png | sed -e "s/^/\"/g;s/$/\"/g" > desc.txt

Can anyone see why my snippet isn't working? When I run it, I get an empty file...

Thanks in advance!

Answer Source

its not sending the full text for your regular expression through to bash because of how python processes and escapes string content, so the best quickest solution would be to just manually escape the back slashes in the string, because python thinks they currently are escape codes. so change this line:

cmd = 'find ' + img_path + '/*.png | sed -e "s/^/\"/g;s/$/\"/g" >'  + file_path + '/desc.txt'

to this:

cmd = 'find ' + img_path + '/*.png | sed -e "s/^/\\"/g;s/$/\\"/g" >'  + file_path + '/desc.txt'

and that should work for you.

although, the comment on your question has a great point, you could totally just do it from python, something like:

import os
import sys    

def main():
    # variables 
    img_path= str(sys.argv[1])
    file_path = str(sys.argv[2]) 

    with open(file_path,'w') as f:
        f.writelines(['{}\n'.format(line) for line in os.listdir(img_path) if line.endswith('*.png')])

if __name__ == "__main__":