【问题标题】:How to fetch the second line data from text file in Python如何在 Python 中从文本文件中获取第二行数据
【发布时间】:2021-06-22 23:06:00
【问题描述】:

如何在 Python 中从文本文件中获取第二行数据。

我有一个文本文件,文件中有一些一行一行的数据_

Dog
Cat
Cow

如何获取第二行“Cat”并存储在python中的变量中

var =    # “Cat”

【问题讨论】:

    标签: python python-3.x string file-handling


    【解决方案1】:

    如果文件很大,可以避免读取所有文件,使用 readline 读取一行两次:

    with open ('file.txt') as file:
        line = file.readline()
        line = file.readline()
    
    print(line)
    

    ...或检查 'seek' 方法以在特定字符索引处开始阅读。

    【讨论】:

      【解决方案2】:

      您可以打开一个文件,然后逐行读取,同时计算行号如下:

      if __name__ == '__main__':
          input_path = "data/animals.txt"
          var = None
          with open(input_path, "r") as fin:
              n_lines = 0
              for line in fin:
                  n_lines += 1
                  if 2 == n_lines:
                      var = line.strip()
                      break
          print(var)
      

      结果:

      Cat
      

      【讨论】:

        【解决方案3】:

        您应该将文本文件与您的 Python 代码放在同一目录中,可能如下:

        with open("animals.txt", "r") as f:
            animals = [line.strip() for line in f]
        
        second_line = animals[1]
        

        现在,变量“second_line”包含了你想要的数据。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多