【发布时间】:2015-06-15 22:24:49
【问题描述】:
更新: 我的问题是由于输入文件具有奇怪的编码。将我的开场白改为“open(os.path.join(root, 'Report.TXT'), 'r', encoding='utf-16')”解决了我的问题
原文
我正在尝试制作一个程序,使我能够更轻松地组织来自某些实验室设备的数据。这个程序递归地在文件夹中移动,找到一个名为Report.TXT的文件,从中获取一些数字,并将它们正确地组织到一个excel文件中。这个文件有很多不相关的信息,所以我只需要抓取它的特定部分(例如第 56 行,字符 72-95)。
这是其中一个 Report.TXT 文件的一部分的示例,其中包含我想要获取的信息(在 ng/uL 列下):
RetTime Type Area Amt/Area Amount Grp Name
[min] [nRIU*s] [ng/ul]
-------|------|----------|----------|----------|--|------------------
4.232 BB 6164.18262 1.13680e-5 7.00746e-1 Compound1
5.046 BV 2.73487e5 1.34197e-5 36.70109 Compound2
5.391 VB 3.10324e5 1.34678e-5 41.79371 Compound3
6.145 - - - Compound4
7.258 - - - Compound5
8.159 - - - Compound6
11.092 BB 3447.12158 2.94609e-5 1.01555 Compound7
Totals : 80.21110
这只是 Report.TXT 的一部分,实际的“Compound1”在真实文件的第 54 行。
我已经设法形成了可以抓取这些并将其作为字符串插入到 excel 文件中的东西:
for rootdir in range(1,tdirs+1):
flask = 0
for root, subFolders, files in os.walk(str(rootdir)):
if 'Report.TXT' in files:
flask += 1
with open(os.path.join(root, 'Report.TXT'), 'r') as fin:
print(root)
for x in range(0,67):
line = fin.readline()
if x == 54:
if "-" in line[75:94]:
compound1 = 0
else:
compound1 = str(line[75:94].strip())
print(compound1)
datasheet.write(int(rootdir)+2,int(flask),compound1)
if x == 56:
if "-" in line[75:94]:
compound2 = 0
else:
compound2 = str(line[75:94].strip())
print(compound2)
datasheet.write(int(tdirs)+int(rootdir)+6,int(flask),compound2)
但是,如果我将 str(line[75:94].strip()) 替换为 float(line[75:94].strip()),则会收到 cannot convert string to float 错误。打印只是为了我自己的故障排除,但似乎没有给我任何额外的信息。
有什么想法可以解决这个问题吗?
【问题讨论】:
-
在该实例中您尝试转换为浮点数的确切字符串是什么?
-
使用我提供的示例 Report.TXT,对应于“Compound1”的字符串将是“7.00746e-1”。我使用 strip() 命令尝试仅隔离数字,因为我的 line[75:94] 命令返回一些空格。
-
啊,我刚刚意识到 python 可能没有将指数识别为正确的浮点数?无论如何,只有小数而没有指数的数字也会出现同样的问题
-
" 7.00746e-1"可以转换为float就好了(顺便说一下,你不需要strip()空格)。你能把有问题的行放在try块中,然后把print(repr(line[75:94].strip()))放在相应的except块中吗? -
感谢您的建议,我认为这是导致问题的原因。当我这样做时,我得到每一行的以下打印输出: 1 0 。 6 9 9 7 4 '\x00\x001\x000\x00.\x006\x009\x009\x007\x004'。我不确定 x001 的东西来自哪里。但是,前面的数字在文本文件中是准确的。