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()
.

- 75,346
- 28
- 201
- 283

- 15,602
- 32
- 87
- 122
-
What files do you want to move? Take a look at http://docs.python.org/library/shutil.html for file operations using Python. – Jan 25 '12 at 13:32
-
Shell script is enough for this – Shiplu Mokaddim Jan 25 '12 at 13:33
-
1If you use shell scripts, read more about pipes and redirection. – Some programmer dude Jan 25 '12 at 13:35
-
I am not talking about creating a seperate .sh file. A combination of `for`, `if`, `file` would be enough. – Shiplu Mokaddim Jan 25 '12 at 13:37
-
2If you're not creating a shell script you shouldn't be using `ls`. In fact, even if you are creating a shell script your should be using `find` for this. – sorpigal Jan 25 '12 at 14:16
3 Answers
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

- 45,586
- 12
- 116
- 142
After skimming the python documentation to run shell command and obtain the output you can use the subprocess module with the check_output
method.
After that you can simple write that output to a file with the standard Python IO functions: File IO in python.

- 9,727
- 3
- 37
- 37
To open a file, you can use the f = open(/Path/To/File)
command. The syntax is f = open('/Path/To/File', 'type')
where 'type' is r for reading, w for writing, and a for appending. The commands to do this are f.read()
and f.write('content_to_write')
. To get the output from a command line command, you have to use popen and subprocess instead of os.system()
. os.system() doesn't return a value. You can read more on popen here.

- 4,460
- 4
- 31
- 50