读/写标题字符串和数值数组

时间:2016-07-19 18:17:32

标签: python arrays numpy

我是Python新手,我无法做一些非常简单的事情。我在这里看到了处理字符串和数字的例子,但没有看到如何处理几行的一个字符串头后跟数字数组。我找到了部分解决方案,但第一行数据部分被切断了。这就是我所做的:

import numpy as np
infil="infile.txt"
outfil="outfile.txt"
fi = open(infil,"r") 
fo = open(outfil,"w")
lines = fi.readlines()
fo.writelines(lines[0:3])
fi.close()
x1, x2, x3, x4, x5, x6, x7 = np.loadtxt(infil, skiprows=3, unpack=True)
# Some computations with those columns of numbers occurs here.
data = np.array([x1,x2,x3,x4,x5,x6,x7]
data = data.T 
np.savetxt(outfil, data, fmt='%f')
fo.close()    

以上几乎也有效。只是上半场了 第一行数据丢失。

非常感谢任何帮助。

谢谢, 比尔

2 个答案:

答案 0 :(得分:0)

是的!解决了!虽然解决方案是优雅的。问题是在3行标题之后有一个输出文件包含许多行格式正确的数据。使用上述算法切断前1.5行数据。我在下面给出的解决方案确实有效,但它并不优雅,因为我使用临时文件将格式化数据行传递给我写入最终输出文件的字符串。任何改进和改进该算法的建议都值得赞赏。到那时,这很好用。

import numpy as np              # Load useful routines for arrays. 

infil="infile.txt"              # Input file name.
tfil ="tmp.txt"                 # Temporary file name.
outfil="outfile.txt"            # Output file name.

fi = open(infil,"r")            # Open input file.
ft = open(tfil,"w")             # Open temporary file for writing into. 
fo = open(outfil,"w")           # Open output file.

lines = fi.readlines()          # Read in the input file.

fi.close()                      # Close input file.




x1, x2, x3, x4, x5, x6, x7 = np.loadtxt(infil, skiprows=3, unpack=True)
                            # Read in and unpack the numerical arrays   from the input file. 

 # Computation with those numerical arrays will occur here when I'm ready.                              


data = np.array([x1,x2,x3,x4,x5,x6,x7])
                            # Pack the data arrays together.

data = data.T                   # Transpose the data into columns.


np.savetxt(tfil, data, fmt='%f\t')        # Write to temporary file. 


ft.close()                      # Close temporary file. 

ft = open(tfil,"r")             # Now open temporary file to read in the formatted data lines.

dlines = ft.readlines()         # Read in the temporary file.

fo.writelines(lines[0:3])       # Write the header to the output file.

fo.writelines(dlines)           # Write the formatted data lines to the output file.

fo.close()                      # Close output file. 

答案 1 :(得分:0)

我想添加一个更优雅的解决方案: java -jar FoodVan.jar 接受在数据之前写入文件的标头字符串。有了这个,你真的不需要那个临时文件:

np.savetxt