为numpy设置路径.savetext -文件名包含循环变量



我试图将更改名称的文件保存到与脚本不同的文件夹中:

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)

现在保存带有循环变量的文件名,我遵循了这篇文章。

我天真地认为使用' and '可以解决问题,然而,如果我这样做,我在正确的文件夹中得到一个文件,但是错误的名称(在这种情况下:"frame_" + str(580 + j) + "to" + str(581 + j) + ".txt)(我想要:frame_580_to_581.txt)。如果我不设置路径,则没有问题。

有没有聪明的方法来克服这个问题?

干杯!

EDIT 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')

我不确定你的例子中的"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', [...]

请注意我如何调整你的单/双引号,以便"字符串字面量"被包装在单(或双)引号中,然后我正确地终止字符串字面量并连接(通过+)变量/int/附加字符串…

希望这是有意义的,但是你可以走很长的路来清理你所得到的,以避免这种类型的混乱。

最终,如果你能让它看起来像:

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

这样更干净更可读。但是,再一次,我没有花时间研究save_field做什么以及argskwargs接受什么,所以我不知道_file_name_other_file_nameother_arg作为示例是否有意义,我只是希望它们有意义!

相关内容

最新更新