我正在尝试使用以下语句读取文件:
input = open("input.txt").read().split('\n')
所以基本上我的目标是逐行读取文件并将结果存储在数组中。当文件不为空时,它工作正常。当输入文件只有一行len(input)
为1时,这是预期的。
但是当文件为空时,len(input)
仍然给出1.我做错了什么?
答案 0 :(得分:3)
您应该使用open("input.txt").readlines()
,而不是open("input.txt").read().split("\n")
。如果您在解释器中尝试"".split("\n")
,则会看到结果为['']
,而不是[]
。
答案 1 :(得分:2)
迭代文件会为您提供行,因此您可以使用:
the_input = list(open("input.txt"))
虽然这会在字符串中包含换行符。
答案 2 :(得分:0)
嗯,这就是split
的工作方式:这种情况正在发生:
>>> ''.split(',')
['']
并且它是一个元素的列表,它是空字符串。
答案 3 :(得分:0)
读取空文件返回if(pSup & D3D11_FORMAT_SUPPORT_RENDER_TARGET)
{
//render target supports that type
}
if(pSup & D3D11_FORMAT_SUPPORT_DEPTH_STENCIL)
{
//depth stencil supports that type
}
,然后拆分该空字符串将返回长度为1的""
。
请改为尝试:
[""]