简体   繁体   English

使用命令行 select 文件,读取文件并将内容存储为矩阵(PYTHON,Visual Studio)

[英]Using Command line to select a file, reading the file and storing contents as a matrix (PYTHON, Visual Studio)

I have a file with N rows and M columns.我有一个包含 N 行和 M 列的文件。 I would like to use the command line (python) to specify the file and then store its contents into a matrix in this form [0,0,0],[0,0,0]...我想使用命令行(python)来指定文件,然后将其内容存储到这种形式的矩阵中 [0,0,0],[0,0,0]...

I have this so far, but when I run in through terminal, it does not ask for the text file.到目前为止我有这个,但是当我通过终端运行时,它不会要求文本文件。

import sys

def read_data(filename):
    with open(filename, 'r') as f:
        data = [[int(num) for num in line.split(',')] for line in f]
    return data

def main():
    if len(sys.argv) < 2:
        print("Usage: {0} <Data Points>".format(sys.argv[0]))
        sys.exit(1)

    file1 = sys.argv[1]

    data_points = read_data(file1)
    print(data_points)

You should pass the file path as an argument when calling your program.调用程序时,您应该将文件路径作为参数传递。

python script.py /myfile

Or whatever arguments your script.py file needs.或者您的script.py文件需要的任何 arguments。

Your script does not call the main() function.您的脚本没有调用main() function。 We define the main() function, but it will not run until called.我们定义了main() function,但它在调用之前不会运行。 I added a call to the main() function at the bottom of the script.我在脚本底部添加了对main() function 的调用。

import sys

def read_data(filename):
    with open(filename, 'r') as f:
        data = [[int(num) for num in line.split(',')] for line in f]
    return data

def main():
    if len(sys.argv) < 2:
        print("Usage: {0} <Data Points>".format(sys.argv[0]))
        sys.exit(1)

    file1 = sys.argv[1]

    data_points = read_data(file1)
    print(data_points)

main()

When you run the script, you will want to run it on the command line using a command that looks similar to this:运行脚本时,您将希望使用类似于以下的命令在命令行上运行它:

$ python3 myscript.py mydata.csv

Where:在哪里:

  • myscript.py is the name of your script myscript.py是您的脚本的名称
  • mydata.csv is the name of your data file mydata.csv是您的数据文件的名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM