Python – writing command line output to file


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

Best Solution

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

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

Using python,

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

However, if you are using python then instead of using ls command you can use os.listdir to list all the files in the directory.

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