简体   繁体   English

Python —从文件读取行并将其拆分

[英]Python — Reading lines from file and split it

I'm trying to split the lines from a .txt file stored locally. 我正在尝试从本地存储的.txt文件中拆分行。 What I do to make a for loop but I want to start the loop on an specific index on the array. 我做了一个for循环,但是我想在数组的特定索引上开始循环。 For example: 例如:

  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

This gives me errors at : file_content[index:] It's there any way to start the loop at specific line from the file_content? 这给我以下错误:file_content [index:]有什么方法可以从file_content的特定行开始循环吗?

The fact it's that the code below works and loops the array : 事实是下面的代码可以工作并循环数组:

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

Could anyone help me please? 有人可以帮我吗?

I've fount the answer! 我已经找到答案了! I didn't call the method .readlines() 我没有调用方法.readlines()

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

You can use lines = open(filepath, 'rb').readlines() to get a list of strings, where each string is a line in your file. 您可以使用lines = open(filepath, 'rb').readlines()来获取字符串列表,其中每个字符串都是文件中的一行。 You can then slice the list at any index you want to only get the lines you are interested in like this: wanted_lines = lines[index:] This will get you all the lines from index to the end of the file. 然后,您可以像这样对列表进行切片:只希望获取感兴趣的行,如下所示: wanted_lines = lines[index:]这将使您获得从索引到文件末尾的所有行。

You can use islice from the itertools module to create a slice over a file (or any iterable): 您可以使用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

see http://docs.python.org/2/library/itertools.html#itertools.islice for more 有关更多信息,请参见http://docs.python.org/2/library/itertools.html#itertools.islice

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM