在我从文件中读取后:
with open(fileName) as f:
for line in f:
print(line.split(",")) #split the file into multiple lists
如何从这些列表中获取一些特定元素?
例如,仅index0为3的元素,但丢弃/忽略之后的任何元素。
发布于 2018-06-15 07:47:06
如果要保存每行中的前三项,可以使用列表理解
with open(fileName) as f:
firstitems = [line.rstrip().split(",")[0:3] for line in f]
请注意,如果一行中的项目少于四个,则需要使用rstrip()
删除最后一个换行符。请注意,"items“都是字符串,即使它们看起来像其他类型。例如,如果您想要整数,则需要将其转换为整数。
然后,您可以打印它们:
for line in firstitems:
print(line)
发布于 2018-06-15 07:36:29
试试下面的代码:
with open('f.txt') as f:
print('\n'.join([i for i in f.read().split(',')[0:3]]))
https://stackoverflow.com/questions/50867244
复制相似问题