I have a file with N rows and M columns. 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]...
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.
Your script does not call the main()
function. We define the main()
function, but it will not run until called. I added a call to the main()
function at the bottom of the script.
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 mydata.csv
is the name of your data file
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.