2013-06-18 65 views
0

我想保存更改名稱爲不同的文件夾的腳本文件是:設置numpy.savetxt路徑 - 文件名包含循環變量

save_field('./cycle_1_580-846/txt/"frame_" + str(580 + j) + "_to_" + str(581 + j) + ".txt"', "Data68_0" + str(580 + j) + ".tif", str(580 + j) + "_to_" + str(581 + j), scale = 1500, width = 0.0025) 

現在保存的文件名與循環變量我跟着this post

我天真地以爲用「和」將解決這個問題,但是,如果我這樣做,我得到的文件夾,但有錯誤名的文件(在這種情況下:‘frame_’+ str(580 + j)+「to」+ str(581 + j)+「.txt)(我想要:frame_580_to_581.txt)。如果我沒有設定路徑,我沒有問題。

有沒有一種巧妙的方法可以解決這個問題?

乾杯!

編輯 j是隻是在一定範圍內的文件(在這種情況下,從0到270,遞增1)

也許這也將有助於

def save_field(filename, background, new_file, **kw): 
""" Saves quiver plot of the data stored in the file 
Parameters 
---------- 
filename : string 
the absolute path of the text file 
background : string 
the absolute path of the background image file 
new_file : string 
the name and format of the new file (png preferred) 

Key arguments : (additional parameters, optional) 
*scale*: [None | float] 
*width*: [None | float] 
""" 

a = np.loadtxt(filename) 
pl.figure() 
bg = mpimg.imread(background) 
imgplot = pl.imshow(bg, origin = 'lower', cmap = cmps.gray) 
pl.hold(True) 
invalid = a[:,3].astype('bool') 

valid = ~invalid 
pl.quiver(a[invalid,0],a[invalid,1],a[invalid,2],a[invalid,3],color='r',**kw) 
pl.quiver(a[valid,0],a[valid,1],a[valid,2],a[valid,3],color='r',**kw) 
v = [0, 256, 0, 126] 
axis(v) 
pl.draw() 
pl.savefig(new_file, bbox_inches='tight') 

回答

0

我不是確定你的例子中的「j」是什麼......但我會做出一些隱含的假設,並從那裏向前移動(也就是說,它看起來像你試圖建立一個增量)。

嘗試以下操作:

save_path = "./cycle_1_580-846/txt/frame_" 
save_file = (str(580) + "_to_" + str(581) + ".txt") 
save_other_file = ("Data68_0" + str(580) + ".tif") 

save_field((save_path + save_file), , save_other_file, (str(580) + "_to_" + str(581)), scale = 1500, width = 0.0025) 

我建議像上面 - 有一些封裝,是有點更容易閱讀,我甚至會進一步去清理save_field()。 ..但我不知道它做了什麼,我不想承擔太多。

您遇到的真正問題是您繼續使用您的產品,因爲您錯誤地將單引號與雙引號混合在一起。

sampleText = 'This is my "double quote" example' 
sampleTextAgain = "This is my 'single quote' example" 

這兩個都是有效的。

但是,你有什麼是:

sampleBadText = '"I want to have some stuff added" + 580 + "together"' 

單引號包裝材料基本上把整個行成一個字符串。所以,難怪爲什麼你的文件被命名爲它的樣子。您需要在適當位置用單/雙引號終止字符串,然後跳回到python內建變量名稱,然後返回到字符串以便連接strings + variables + strings

否則都爲你工作,這就是它會開始看起來像:

save_field('./cycle_1_580-846/txt/frame_' + str(580 + j) + '_to_' + str(581 + j) + '.txt', [...] 

注意我是如何調整你的單/雙引號,這樣的方式「字符串文字」被包裹在單(或雙)引號,然後我正確地終止字符串字符串和連字符(通過+)變量/ ints /附加字符串...

希望這是有道理的,但你可以走很長的路要清理你所要避免的這種類型的混淆。

最後,如果你能得到它看起來像:

save_field(_file_name, _other_file_name, other_arg, scale=1500, width=0.0025) 

這是更清潔,更具有可讀性。但是,我再也沒有花時間去調查save_field的功能,以及它接受的是什麼,所以我不知道_file_name_other_file_nameother_arg甚至是有意義的例子,我只是希望它們能夠做到!

+0

謝謝你的深入答案,我會給你一個建議,讓你知道它是如何工作的! 爲「和'用法輸入乾杯,我認爲,因爲我有我所有的」「和」關閉它不會是一個問題! –

+0

工作就像一個魅力!乾杯! –

+0

非常好。很高興我能幫助!祝你好運一切。 –