【问题标题】:Python -- Reading lines from file and split itPython - 从文件中读取行并将其拆分
【发布时间】:2013-07-19 08:27:22
【问题描述】:

我正在尝试从本地存储的 .txt 文件中拆分行。我做了一个 for 循环,但我想在数组上的特定索引上开始循环。例如:

  file_content = open('files/filefinal1_test.txt')
  counter = 0
  total_lines = 0
  global l
  index = 0 if l == "" else file_content.index(l)

  for line in file_content[index:]: 
    l = line
    array_line =line.split('", "')
    array_line[0] = array_line[0].replace('"', '')
    array_line[1] = array_line[1].replace('"', '')
    array_line[2] = array_line[2].replace('"', '')
    array_line[3] = array_line[3].replace('"', '')
    if (send_req(papi, array_line) == 1): 
        counter = counter + 1 
    total_lines = total_lines + 1

这给了我错误:file_content[index:] 有没有办法从 file_content 的特定行开始循环?

事实上,下面的代码可以运行并循环数组:

for line in file_content: 
        l = line
        array_line =line.split('", "')
        array_line[0] = array_line[0].replace('"', '')
        array_line[1] = array_line[1].replace('"', '')
        array_line[2] = array_line[2].replace('"', '')
        array_line[3] = array_line[3].replace('"', '')
        if (send_req(papi, array_line) == 1): 
            counter = counter + 1 
        total_lines = total_lines + 1

谁能帮帮我?

【问题讨论】:

    标签: python arrays file split


    【解决方案1】:

    我找到了答案!我没有调用方法 .readlines()

    file_content = file_content.readlines()
    for lines in file_content[0:]:
         #stuff
    

    【讨论】:

    • open 为您提供文件对象,readlines 为您提供文件中的行列表:docs.python.org/2/library/stdtypes.html#file.readlines
    • for lines in file_content[0:]:可以写成for lines in file_content:
    • 从长远来看,重用变量名来包含不同的类型可能不是一个好主意。这很容易被忽视。
    • @Frodon 不,file_content 它不是一个数组,所以它不一样
    【解决方案2】:

    您可以使用lines = open(filepath, 'rb').readlines() 获取字符串列表,其中每个字符串是文件中的一行。然后,您可以在任何索引处对列表进行切片,只获取您感兴趣的行,如下所示:wanted_lines = lines[index:] 这将获取从索引到文件末尾的所有行。

    【讨论】:

      【解决方案3】:

      您可以使用itertools 模块中的islice 在文件(或任何可迭代的)上创建切片:

      import itertools
      with open('file') as f:
          for line in itertools.islice(f, 3, 5): # 3 and 5 are the start and stop points
              print line
      

      http://docs.python.org/2/library/itertools.html#itertools.islice 了解更多

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-19
        • 1970-01-01
        • 2016-04-11
        • 2013-05-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多