我想保存生成的图表,其名称与输入文件的名称相同。输入是通过命令行,所以我不确定如何做。
#!/usr/bin/python
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from numpy import arange,array,ones#,random,linalg
from pylab import plot,show
from scipy import stats
from sys import argv
a = argv[1]
b = argv[2]
list1 = open(a)
list2 = open(b)
xi = list1.read().splitlines()
filter(None,xi)
y = list2.read().splitlines()
filter(None,y)
xi = [float(xk) for xk in xi]
y = [float(yk) for yk in y]
slope, intercept, r_value, p_value, std_err = stats.linregress(xi,y)
print 'r value', r_value
line = slope*xi+intercept
plot(xi,line,'r-',xi,y,'o')
plt.savefig('a')
我的输入是number001.txt,我希望输出为number001.png。
谢谢!
答案 0 :(得分:5)
sys.argv
获取输入文件名并使用相同文件名保存输出的简单示例。
e.g。
import sys
if __name__=="__main__":
print "argument:", sys.argv
inputfile = sys.argv[1]
print "inputfile:", inputfile
outputfile = inputfile.split(".")[0] + "__output.txt"
print "outputfile:", outputfile
with open(outputfile, "wb" ) as fp:
fp.write("some content")
输出:
vivek@vivek:~/Desktop/stackoverflow$ python 25.py test.txt
argument: ['25.py', 'test.txt']
inputfile: test.txt
outputfile: test__output.txt
os
模块也有路径拆分方法。
e.g。
>>> import os
>>> os.path.splitext("input.txt")
('input', '.txt')