我正在创建一个读取文件的程序,如果文件的第一行不是空白,则会读取接下来的四行.在这些行上执行计算,然后读取下一行.如果该行不为空,则继续.但是,我收到此错误:
ValueError: invalid literal for int() with base 10: ''.
它正在读取第一行但不能将其转换为整数.
我该怎么做才能解决这个问题?
代码:
file_to_read = raw_input("Enter file name of tests (empty string to end program):")
try:
infile = open(file_to_read, 'r')
while file_to_read != " ":
file_to_write = raw_input("Enter output file name (.csv will be appended to it):")
file_to_write = file_to_write + ".csv"
outfile = open(file_to_write, "w")
readings = (infile.readline())
print readings
while readings != 0:
global count
readings = int(readings)
minimum = (infile.readline())
maximum = (infile.readline())
Run Code Online (Sandbox Code Playgroud)
小智 261
仅供记录:
>>> int('55063.000000')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '55063.000000'
Run Code Online (Sandbox Code Playgroud)
我来这里......
>>> float('55063.000000')
55063.0
Run Code Online (Sandbox Code Playgroud)
必须使用!
Sil*_*ost 53
Pythonic迭代文件并转换为int的方法:
for line in open(fname):
if line.strip(): # line contains eol character(s)
n = int(line) # assuming single integer on each line
Run Code Online (Sandbox Code Playgroud)
你要做的事情稍微复杂一些,但仍然不是直截了当的:
h = open(fname)
for line in h:
if line.strip():
[int(next(h).strip()) for _ in range(4)] # list of integers
Run Code Online (Sandbox Code Playgroud)
这样它当时处理5行.使用h.next()而不是next(h)Python 2.6之前.
你的原因ValueError是因为int无法将空字符串转换为整数.在这种情况下,您需要在转换之前检查字符串的内容,或者除了错误之外:
try:
int('')
except ValueError:
pass # or whatever
Run Code Online (Sandbox Code Playgroud)
Pet*_*ter 50
以下内容在python中完全可以接受:
intfloatfloatintfloat但是,你得到一个ValueError,如果你传递的字符串表示浮到int,或任何一个字符串表示,但一个整数(包括空字符串).如果你确实想要将float的字符串表示传递给a int,正如@katyhuff指出的那样,你可以先转换为float,然后转换为整数:
>>> int('5')
5
>>> float('5.0')
5.0
>>> float('5')
5.0
>>> int(5.0)
5
>>> float(5)
5.0
>>> int('5.0')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'
>>> int(float('5.0'))
5
Run Code Online (Sandbox Code Playgroud)
raj*_*mar 11
原因是你得到一个空字符串或字符串作为参数进入int检查之前它是空的还是包含字母字符,如果它包含而不是简单地忽略该部分.
Bra*_*123 11
我找到了解决方法。Python会将数字转换为浮点数。只需先调用float,然后将其转换为int即可:
output = int(float(input))
所以如果你有
floatInString = '5.0'
Run Code Online (Sandbox Code Playgroud)
你可以将其转换为int与floatInInt = int(float(floatInString))