writing command line output to file

杀马特。学长 韩版系。学妹 提交于 2019-12-04 01:21:47

问题


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


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/9003522/writing-command-line-output-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!