Write command line to file

I am writing a script to clean my desktop, moving files based on file type. The first step would seem to be ls -1 /Users/user/Desktop(I'm on Mac OSX). So using Python, how do I run a command and then write the output to a file in a specific directory? Since this will be undocumented and I will be the only user, I do not mind (prefer?) If he uses os.system().

+5
source share
3 answers

You can redirect standard output to any file using the command >.

$ ls /Users/user/Desktop > out.txt

Using python,

os.system('ls /Users/user/Desktop > out.txt')

However, if you use python, instead of using the command, lsyou can use os.listdirto display all the files in the directory.

path = '/Users/user/Desktop'
files = os.listdir(path)
print files
+13

python subprocess check_output.

IO Python: File IO python.

+4

, f = open(/Path/To/File). f = open('/Path/To/File', 'type') 'type' - r , w a . : f.read() f.write('content_to_write'). , popen subprocess os.system(). os.system() . popen .

+1

All Articles