【问题标题】:Is there a way to remove entire parts of lines from a text file in Python, then remove certain parts of the rest?有没有办法从 Python 中的文本文件中删除整个行的部分,然后删除其余部分?
【发布时间】:2025-11-26 15:35:01
【问题描述】:

我有一个如下所示的文本文件:

                               Close
Datetime                            
2021-07-02 09:30:00-04:00  93.080002
2021-07-02 09:30:00-04:00  93.080002
2021-07-02 09:31:00-04:00  93.026001
2021-07-02 09:32:00-04:00  92.405403
2021-07-02 09:33:00-04:00  92.370003

我希望它看起来像这样:

93.080002
93.080002
93.026001
92.405403
92.370003

有没有办法在 Python 中通过擦除前 2 行然后只擦除其余的时间来做到这一点?提前致谢。

【问题讨论】:

  • 是的,有。将文件读入行列表。删除列表的前两个元素。对于所有其余的行,您可以使用split() 来获取最后一个字段。将此结果写回文件。
  • 这些步骤都不应该很复杂。

标签: python file text erase


【解决方案1】:

给定:

$cat ur_file
                               Close
Datetime                            
2021-07-02 09:30:00-04:00  93.080002
2021-07-02 09:30:00-04:00  93.080002
2021-07-02 09:31:00-04:00  93.026001
2021-07-02 09:32:00-04:00  92.405403
2021-07-02 09:33:00-04:00  92.370003

你可以这样做:

with open(ur_file) as f_in:
    data=[line.strip().split()[-1] for i,line in enumerate(f_in) if i>1]

结果:

>>> data
['93.080002', '93.080002', '93.026001', '92.405403', '92.370003'] 

或:

>>> print('\n'.join(data)) 
93.080002
93.080002
93.026001
92.405403
92.370003

如果您想要一个将输出写入文件的过滤器:

with open(ur_file) as f_in, open(out_file, 'w') as f_out:
    for i, line in enumerate(f_in):
        if i>1:
            f_out.write(f'{line.split()[-1]}\n')

这会产生所需的输出文件。

【讨论】:

    【解决方案2】:

    使用`test.txt 作为输入文件:

    Close
    Datetime                            
    2021-07-02 09:30:00-04:00  93.080002
    2021-07-02 09:30:00-04:00  93.080002
    2021-07-02 09:31:00-04:00  93.026001
    2021-07-02 09:32:00-04:00  92.405403
    2021-07-02 09:33:00-04:00  92.370003
    
    
    

    使用代码:

    with open('test.txt' , 'r') as handle: #open test.txt file as handle, read mode and text mode (default)
        pippo = handle.readlines()         #reads the handle file all at once into lines
    
    with open('res.txt' , 'w+') as whandle: #open res.txt file to write to it, write mode  and text mode (default)
        
        for i in range(0,len(pippo)):        # loops over the file lines from 0 to lenght of readlines alias number of lines 
            if i > 1:                        # starts at second line on (lines start at zero su skips line 0 and line 1
                print(pippo[i].split()[2])   # print line i splitted by whitespace third element: the number you are looking for 
                whandle.write(pippo[i].split()[2]+'\n') #writes the above lines adding \n line terminator to res.txt file
    

    将结果写入res.txt 文件:

    93.080002
    93.080002
    93.026001
    92.405403
    92.370003
    
    
    

    【讨论】:

    • 纯代码答案并不是特别有用。请添加一些关于此代码如何解决问题的描述。
    • @SvenEberth 现在好点了吗? (英语不是我的母语,如果这是一个合理的答案,请告诉我)干杯