将命令行输出写入文件 [英] writing command line output to file

查看:89
本文介绍了将命令行输出写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个脚本来清理我的桌面,并根据文件类型移动文件.第一步似乎是ls -1 /Users/user/Desktop(我在Mac OSX上).因此,如何使用Python运行命令,然后将输出写入特定目录中的文件?由于这将是无证的,并且我将是唯一的用户,因此我不介意(首选?)是否使用os.system().

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

推荐答案

您可以在命令中使用>将标准输出重定向到任何文件.

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

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

使用python

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

但是,如果您使用的是python,则可以使用os.listdir列出目录中的所有文件,而不是使用ls命令.

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

这篇关于将命令行输出写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆