【问题标题】:Reading in a file of one-word lines in python在python中读取一个单词行的文件
【发布时间】:2018-08-05 08:22:18
【问题描述】:

只是好奇是否有更清洁的方法可以做到这一点。我有一个文件中的单词列表,每行一个单词。 我想读入它们并将每个单词传递给一个函数。 我目前有这个:

f = open(fileName,"r");
lines = f.readlines();
count = 0
for i in lines:
    count += 1
    print("--{}--".format(i.rstrip()))
    if count > 100:
        return

我有没有一种方法可以更快地阅读它们而不在每一行上使用 rstrip?

【问题讨论】:

  • 更快是什么意思?为什么返回没有函数?你总是只想要前 100 行吗?

标签: string python-3.x file file-upload strip


【解决方案1】:
with open(fileName) as f:
    lines = (line for _, line in zip(range(100), f.readlines()))
    for line in lines:
        print('--{}--'.format(line.rstrip()))

我会这样做。请注意上下文管理器(with/as 语句)和生成器理解只给我们前 100 行。

【讨论】:

    【解决方案2】:

    类似于Patrick's的回答:

    with open(filename, "r") as f:
        for i, line in enumerate(f):
            if i >= 100:
                break
            print("--{}--".format(line[:-1]))
    

    如果您没有.strip() 并且知道长度行终止符,则可以使用[:-1]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-16
      • 1970-01-01
      • 1970-01-01
      • 2012-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多