如何在Python中读取块数据?
我在读取数据文件时遇到了问题:
///
* ABC Names
A-06,B-18,
* Data
1.727e-01, 1.258e-01, 2.724e-01, 2.599e-01,-3.266e-01,-9.425e-02,-6.213e-02, 1.479e-01,
1.219e-01, 1.174e-01, 2.213e-01, 2.875e-01,-2.306e-01,-3.900e-03,-5.269e-02, 7.420e-02,
2.592e-01, 2.513e-01, 2.242e-01, 2.620e-01,-1.346e-01,-6.844e-02,-4.139e-02, 9.502e-02,
1.981e-01, 1.937e-01, 2.336e-01, 1.617e-01,-4.240e-02, 2.285e-02, 1.878e-02, 1.064e-01,
9.562e-02, 6.727e-02, 1.135e-01, 6.765e-02,-7.850e-02, 6.711e-02, 1.317e-02, 8.367e-02,
* Starting position
-.5000E+01
///
这个代码是在Python中运行的吗?我试过用 readline()
和 readlines()
这两个函数,但没有得到结果。
5 个回答
0
假设文件名是“abc.txt”,并且它在当前目录下;那么下面这个Python脚本:
f = open("abc.txt")
all_lines = f.readlines()
会把文件里的所有行读取到一个字符串列表 all_lines
中,每一行的结尾都会有 \n
。
至于你接下来想要做什么,我们无法猜测,除非你告诉我们。不过你问的那部分,关于读取文件的内容,应该是没问题的。
1
这个方法应该适用于名字为 'a'、'b' 和 'c' 的文件。它会创建一个字典,字典里的键就是这些块的标题,像这样:
{'a':['line1','line2'],'b':['line1'],'c':['line1','line2','line3']}
代码:
block_names = ['b','a','c']
for line in open('file.txt'):
block_dict = {} #dict to populate with lists of lines
block = [] # dummy block in case there is data or lines before first block
ck_nm = [blk_nm for blk_nm in block_names if line.startswith(blk_nm)] #search block names for a match
if ck_nm: # did we find a match?
block_dict[ck_nm[0]] = block = [] # set current block
else:
block.append(line) #..or line.split(',') ..however you want to parse the data
2
这里有一段代码的猜测,它可能会加载这个文件的类型,这段代码应该是比较稳健的:
f = open("mdata.txt")
data_dict = {}
section = None
data_for_section = ""
for line in f:
line = line.strip() #remove whitespace at start and end
if section != None and (line[0] == "*" or line == "///"):
# if we've just finished a section, put whatever we got into the data dict
data_dict[section] = [bit for bit in data_for_section.split(",") if bit != ""]
if line[0] == "*":
# "*" denotes the start of a new section, probably, so remember the name
section = line [2:]
data_for_section = ""
continue
data_for_section += line
f.close()
#got the data, now for some output
print "loaded file. Found headings: %s"%(", ".join(data_dict.keys()))
for key in data_dict.keys():
if len(data_dict[key])>5:
print key, ": array of %i entries"%len(data_dict[key])
else:
print key, ": ", data_dict[key]
这段代码会输出你文件中的内容:
loaded file. Found headings: ABC Names, Data, Starting position ABC Names : ['A-06', 'B-18'] Data : array of 40 entries Starting position : ['-.5000E+01']
当然,如果是数据和起始位置的话,你可能想把数据字符串的列表转换成浮点数:
startingPosition = float(data_dict["Starting position"][0])
data_list_of_floats = map(float, data_dict["Data"])
至于ABC名称以及它们如何与文件的其他部分结合,我们还需要更多的信息。