简体   繁体   English

如何 append 仅从给定起点将数据从文本文件到列表,而不是使用 python 附加完整文件

[英]How to append the data from a text file to a list only from a given starting point rather then appending full file using python

I want to append data from text file to a list from a given starting point.我想将 append 数据从文本文件到给定起点的列表。 The stating point string can be anywhere in the file.起始点字符串可以在文件中的任何位置。 i want to append the data from that starting point.我想从那个起点开始 append 数据。 I tried by using startswith method:我尝试使用startswith方法:

list1=[] 
TextFile = "txtfile.txt"
# open the file for data processing
with open(TextFile,'rt',encoding="utf8") as IpFile:
    for i,j in enumerate(IpFile):
        if(j.startswith("Starting point")):
            list1.append(str(j).strip()) 
            i+=1      

but it only append the starting point.但它只是 append 的起点。 i want to append the all data from starting point.我想 append 从起点开始的所有数据。 How to do that?怎么做?

Use a boolean variable使用 boolean 变量

list1=[] 
TextFile = "txtfile.txt"
doAppend = False
# open the file for data processing
with open(TextFile,'rt',encoding="utf8") as IpFile:
    for i,j in enumerate(IpFile):
        if(j.startswith("Starting point")):
            doAppend = True
        if doAppend:
            list1.append(str(j).strip()) 
            i+=1      

You could do it without a bool as well by break ing the for loop and then reading the rest of the file.您也可以通过break for循环然后读取文件的 rest 来在没有bool的情况下执行此操作。

list1 = [] 
text_file = "txtfile.txt"
# rt is the default so theres no need to specify it
with open(text_file, encoding="utf8") as ip_file:
    for line in ip_file:
        if line.startswith("Starting point"):
            break
    # read the rest of the file
    remainder = ip_file.read()
    # extend the list with the rest of the file split on newlines
    list1.extend(remainder.split('\n'))

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

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