若文件包含的行数不超过n行,则更改变量



我目前有一些代码可以获取文件中第一行之后的所有行,并将其保存到变量resourceslist中。我想添加一些代码,说明如果文件中只有一行,那么给变量resourceslist值"oneline">

with open('filepaths', "r+") as f:
if index + 1 > len(f):
for _ in range(1):
next(f)
for lines in f:
resourceslist = f.read()
else:
resourceslist = "oneline"

您可以编写以下内容;第一个for循环是不必要的,因为它实际上永远不会循环,第二个循环是不需要的,因为您希望将文件的全部(剩余(内容读取到resourceslist中,而无需在剩余行上迭代。

with open('filepath') as f:
next(f)  # Skip the first line
resourceslist = f.read()
if not resourceslist:  # i.e., f.read() returned the empty string
resourceslist = "oneline"

最新更新