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

查看:46
本文介绍了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 模块是一个很好的选择,它将从命令行获取任何或所有文件名,并给出指定的文件将内容添加到您的脚本中,就好像它们是一个大文件一样.

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

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

更多信息此处.

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

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