Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 202
tkbx Avatar asked Jan 25 '12 13:01

tkbx


People also ask

How do you write the output of a command to a file?

Redirect Output to a File Only To redirect the output of a command to a file, type the command, specify the > or the >> operator, and then provide the path to a file you want to the output redirected to. For example, the ls command lists the files and folders in the current directory.

How do I save a terminal output to a file?

To do that, press the “File” button in the menu bar and click “Save output as … “ This will open a window dialog where you can save the terminal output. From there, you can pick where you want to save the file.

How do you write output to a file in Linux?

In Linux, for redirecting output to a file, utilize the ”>” and ”>>” redirection operators or the top command. Redirection allows you to save or redirect the output of a command in another file on your system. You can use it to save the outputs and use them later for different purposes.


2 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
like image 75
taskinoor Avatar answered Oct 27 '22 00:10

taskinoor


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.

like image 32
BergmannF Avatar answered Oct 26 '22 22:10

BergmannF