我使用下面的腳本來提取一些軌跡文件中的數據並將數據轉儲到新文件。我可以使用指令「>」將結果重定向到一個文件中,但是我需要爲超過2000個文件執行此操作。爲了讓事情變得容易,我嘗試打開一個文件,讓python本身將結果導入文件。重定向成果轉化爲文件
爲了實現我添加一條線,在該地點,(##)中的代碼,以打開文件,如下所示。 另外我添加了一行來將結果導入文件,如下面的代碼所示,包含(###)。
#!/usr/bin/env python
'''
always put -- #!/usr/bin/env python -- at the shebang
'''
from Scientific.IO.NetCDF import NetCDFFile as Dataset
import itertools as itx
inputfile = "../traj-waters/waters1445-MD001-run1000.traj"
for FRAMES in range(0,2):
frame = FRAMES
text_file = open("velo-Output.dat", "w") (##)
#inputfile = 'mdcrd'
ppp = inputfile
def grouper(n, iterable, fillvalue=None):
args = [iter(iterable)] * n
return itx.izip_longest(fillvalue=fillvalue, *args)
formatxyz = "%12.7f%12.7f%12.7f%12.7f%12.7f%12.7f"
formatxyz_size = 6
formatxyzshort = "%12.7f%12.7f%12.7f"
formatxyzshort_size = 3
#ncfile = Dataset(inpitfile, 'r')
ncfile = Dataset(ppp, 'r')
variableNames = ncfile.variables.keys()
#print variableNames
shape = ncfile.variables['coordinates'].shape
'''
do the header
'''
print 'title ' + str(frame)
print "%5i%15.7e" % (shape[1],ncfile.variables['time'][frame])
'''
do the velocities
'''
try:
xyz = ncfile.variables['velocities'][frame]
temp = grouper(2, xyz, "")
for i in temp:
z = tuple(itx.chain(*i))
if (len(z) == formatxyz_size):
print formatxyz % z
text_file.write('formatxyz\n' % z)) (###)
elif (len(z) == formatxyzshort_size): print formatxyzshort % z
except(KeyError):
xyz = [0] * shape[2]
xyz = [xyz] * shape[1]
temp = grouper(2, xyz, "")
for i in temp:
z = tuple(itx.chain(*i))
if (len(z) == formatxyz_size): print formatxyz % z
elif (len(z) == formatxyzshort_size): print formatxyzshort % z
x = ncfile.variables['cell_angles'][frame]
y = ncfile.variables['cell_lengths'][frame]
text_file.close()
但是,如果我運行下面的代碼,我會得到錯誤。
Traceback (most recent call last):
File "./Nctorst-onlyVelo.py", line 73, in <module>
text_file.write(str('formatxyz\n' % z))
TypeError: not all arguments converted during string formatting
因爲我是新手進入python我發現丟失糾正這個問題。
提前感謝您的幫助。 問候
你實際上並沒有使用'z'在字符串中... – Volatility
感謝您的指示。它正在工作。另外我改變text_file =打開(「齶Output.dat」,「W」),以text_file =打開(「齶Output.dat」,「一個」),使得在下一循環中的數據被追加到follwoing線。但是這不會發生。新數據從同一行開始(從最後一行的結尾開始)。如何使用新行將進行中的數據寫入文件? – Vijay