[英]ValueError: could not convert string to float: '' when reading file
I'm trying to read each line text file with a single number on each line and convert the number into a list of integers.我正在尝试读取每一行文本文件,每一行都有一个数字,并将该数字转换为整数列表。 The test file I wrote contains these numbers:
我写的测试文件包含这些数字:
1
23
567
4000
I use this code in my main function to read the file and write the output of my function est() into another output file.我在我的主 function 中使用此代码读取文件并将我的 function est() 的 output 写入另一个 output 文件。
with open(in_path, "r", encoding = "utf-8") as f_in, \
open(out_path, "w", encoding = "utf-8") as f_out:
for line in f_in:
word1 = est(line)
f_out.write(f"{line} = {est(line)}")
The error occurs when I pass the line to est() as the argument num to convert the string into the list of integers in est().当我将行作为参数 num 传递给 est() 以将字符串转换为 est() 中的整数列表时发生错误。
for i in num:
num_list.append(int(float(i)))
This causes the error ValueError: could not convert string to float: ''这会导致错误 ValueError: could not convert string to float: ''
Per the comments:根据评论:
with open(in_path, "r", encoding = "utf-8") as f_in, \
open(out_path, "w", encoding = "utf-8") as f_out:
for line in f_in:
line = line.strip():
if not line:
continue
word1 = est(line)
f_out.write(f"{line} = {word1}")
Should work.应该管用。 Here we skip blank lines, and whitespace on the line.
这里我们跳过空白行,并在行上添加空格。
You can try to strip line first:您可以先尝试剥离线:
with open(in_path, "r", encoding = "utf-8") as f_in, \
open(out_path, "w", encoding = "utf-8") as f_out:
for line in f_in:
word1 = est(line.strip())
f_out.write(f"{line} = {est(line)}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.