我有一个从文本文件中读入的浮点数列表.经过一些数据处理后,我使用以下命令将列表写入文件:
for val in flist:
sa = '{0}'.format(val)
fout.write(sa)
Run Code Online (Sandbox Code Playgroud)
对于特定的输入文件,输出文件在字符串中将包含":".我已经运行调试并在失败时停止了脚本.值应为58710000.0
[Dbg]>>> print val[464]
5870:000.0
[Dbg]>>> fa = val[464]
[Dbg]>>> print fa
5870:000.0
[Dbg]>>>
[Dbg]>>> fa = fa + 1
[Dbg]>>> print fa
58710001.0
[Dbg]>>> fa = fa - 1
[Dbg]>>> print fa
5870:000.0
Run Code Online (Sandbox Code Playgroud)
这仅适用于某些文件和浮点数
有什么建议?
我遇到了和这个家伙一样的问题,也可能是这个家伙,但我正在分享一些代码并回答问题!
我在批处理作业中有一些代码,它通过pyodbc从Microsoft Access数据库中读取字段,并准备输出以供显示.
这是一个片段.请注意断言.
def format_currency(amount):
if amount is None:
return ""
else:
result = "$%.2f" % amount
assert ":" not in result, (
"That's weird. The value %r of class %s is represented as %s" %
(amount, amount.__class__, result))
return result
Run Code Online (Sandbox Code Playgroud)
当我运行它时,它成功处理100,000行然后失败:
AssertionError: That's weird. The value Decimal('54871.0000') of class <class
'decimal.Decimal'> is represented as $54870.:0
Run Code Online (Sandbox Code Playgroud)
注意异常的结肠.它很少发生 - 大约有300,000条记录中的一次.
当我试图隔离它时,它当然有效.
from decimal import Decimal
print "$%.2f" % Decimal('54871.0000')
Run Code Online (Sandbox Code Playgroud)
$ 54871.00
Access中字段的类型是:
我真的很困惑为什么会发生这种情况:
Python 3.7.1 (default, Nov 5 2018, 14:07:04)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: 10**3.5
ValueError: could not convert string to float: 3.5
Run Code Online (Sandbox Code Playgroud)
有人能发光吗?正如你所看到的,这是一个简单的输入 - 我认为它是一个浮点文字.
我试图消除ipython的复杂性,并以隔离模式运行,但仍然:
python3 -I -c "float('3.5')"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ValueError: could not convert string to float: '3.5'
Run Code Online (Sandbox Code Playgroud)
我的python3.7坏了,我的理解是破碎的,还是我在看什么?
我通过将显示的代码放入文件并将其转换为绿色来排除编码问题.这是干净的ascii,应该是0x2e一个点,一个点,0x0a一个行结束:
xxd testfile.py
00000000: 332e 350a 3.5.
python3 -I testfile.py …Run Code Online (Sandbox Code Playgroud)