PYTHON从命令行获取文件 [英] PYTHON get files from command line

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

问题描述

当您运行Python代码时,如何从命令行获取文件名?就像你的代码打开一个文件并读取行,但文件不同,每当你运行它,你怎么说:

How do you get a file name from command line when you run a Python code? Like if your code opens a file and reads the line, but the file varies whenever you run it, how to you say:

python code.py input.txt

因此代码分析input.txt?在实际的Python代码中你需要做什么?我知道,这是一个非常模糊的问题,但我真的不知道如何更好地解释它。

so the code analyzes "input.txt"? What would you have to do in the actual Python code? I know, this is a pretty vague question, but I don't really know how to explain it any better.

推荐答案

伟大的选项是 fileinput 模块,它将从命令行获取任何或所有文件名,然后将内容提供给您的脚本,就像它们是一个大文件。 p>

A great option is the fileinput module, which will grab any or all filenames from the command line, and then give the contents to your script as though they were one big file.

import fileinput
for line in fileinput.input():
    process(line)

详情请参阅这里

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

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