我希望我的程序能够根据命令行参数从 .txt 文件中提取一列文本。
例如,假设我有一个这样的 fruits.txt 文件,
Apple Pear Watermelon
Orange Grapes Banana
在命令行中,如果我要运行 python my_program.py 1 fruits.txt 我希望输出只是第一列, 例如
Apple
Orange
如果它是 python my_program.py 3 fruits.txt,我会期望输出,
Watermelon
Banana
然后说我碰巧也有一个格式相同的 veg.txt 文件...例如
Broccoli Cabbage Asparagus
Spinach Rocket Cucumber
然后在命令行中,如果我执行 python 2 veg.txt,我希望会发生同样的情况 并得到,
Cabbage
Rocket
到目前为止,我只知道如何静态地执行此操作。 IE。我必须硬编码
file = open("fruits.txt", "r") 并专门打印字段。
例如
file = open("fruits.txt", "r")
for line in file:
fields = line.split(" ")
col1 = fields[0]
col2 = fields[1]
col3 = fields[2]
col4 = fields[3]
print(col1)
file.close()
请您参考如下方法:
您可以使用 os 模块中的 argv。
print_col.py:
import os
column, filename = os.argv[1:3] # check the actually number of command arguments
with open(filename, 'r') as f:
print([line.split()[column - 1] for line in f.readlines()]) # make sure the column number doesn't beyond the actually column count in the file
您可以使用此命令调用此脚本 python print_col.py 1 test.txt。
