来自txt文件的参数

时间:2018-06-14 13:21:51

标签: python python-2.7

我想用这种语法从文本文件加载参数:

  

A·B @Ç
  A·B @Ç
  A·B @ç

目前,我的代码如下所示:

with requests.session() as c:
    a = sys.argv[1]
    b = sys.argv[2]
    c = sys.argv[3]
try:
    ...

我调用这样的脚本:

$ python script.py a b c

但是我想修改我的脚本,以便它只能运行一次并消耗参数文本文件的每一行。

1 个答案:

答案 0 :(得分:3)

将路径传递给参数文件,作为脚本的命令行参数。然后打开该文件,从每一行中提取String s = "Century Gothic#12,75#True#FFFFFFFF"; String[] parts = s.split("#"); //parts[2] = "FFFFFFFF" ab

以下是一个例子:

c

然后你会像这样调用你的脚本:

def main(argv=None):
    # Get the file path.
    file_path = argv[1]

    # Open the file.
    with open(file_path) as argfile:
        for line in argfile:
            # Remove any leading or trailing whitespace.
            line = line.strip()

            # Extract a, b, and c.
            a = line.split('#')[0]
            b = line.split('#')[1].split('@')[0]
            c = line.split('@')[1]

            # Perform some action with a, b, and c.