根据第一列从文本文件中提取行到 Python 中的文本

Extracting lines from a text file based on first column to text in Python

我正在使用 Windows 7.0 并安装了 Python 3.4。我对 Python 很陌生。这是我的清单。这是一个价格文件。我有数以千计的这些,但现在一直在努力让它在一个上工作。

我试图只提取以 hfus、ious 或 oaus 开头的行。

caus    123456  99.872300000        2
gous    1234567 99.364200000        2
oaus    891011  97.224300000        2
ious    121314  96.172800000        2
hfus    151617  99081.00            2
hfus    181920  1.000000000         2

这是想要的结果。

oaus    891011  97.224300000        2
ious    121314  96.172800000        2
hfus    151617  99081.00            2
hfus    181920  1.000000000         2

这是我到目前为止所写的内容,但它不起作用。我还想它是否会遍历每个文件并用截断的列表覆盖现有文件,并用它的原始名称保存它。文件 033117.txt 代表一个日期。每个文件都保存为 mmddyy.txt。让它在所有文件上工作是理想的,但现在如果我能让它在一个文件上工作那就太好了。

inFile = open("033117.txt")
outFile = open("result.txt", "w")
buffer = []
keepCurrentSet = True
for line in inFile:
    buffer.append(line)
    if line.startswith("hfus"):
        if line.startswith("oaus"):
            if line.startswith("ious"):
        if keepCurrentSet:
            outFile.write("".join(buffer))
        keepCurrentSet = True
        buffer = []
    elif line.startswith(""):
        keepCurrentSet = False
inFile.close()
outFile.close()

试试这个查询:

inFile = open("033117.txt")
outFile = open("result.txt", "w")
for line in inFile.readlines():
    if line.startswith("hfus"):
        outFile.write(line)
    if line.startswith("oaus"):
        outFile.write(line)
    if line.startswith("ious"):
        outFile.write(line)
inFile.close()
outFile.close()

即使是 python 的新手,所以可能有很多更好的解决方案,但这应该可行。

我建议在打开文件对象时使用with语句,这样您就不需要显式关闭文件,当退出缩进块时它会自动为您关闭。
从一个文件中读取和过滤并将结果写入另一个文件(不覆盖同一个文件)可以通过使用 list comprehension 并选择适当的行来完成,这些行提供了更简洁的方法来完成任务:

with open("033117.txt", 'rt') as inputf, open("result.txt", 'wt') as outputf:    
    lines_to_write = [line for line in inputf if line.split()[0] in ("hfus", "ious", "oaus")]
    outputf.writelines(lines_to_write)

如果您想覆盖文件而不是打开一个新的附加文件并写入,请执行以下操作:

with open('033117.txt', 'r+') as the_file: 
    lines_to_write = [line for line in the_file if line.split()[0] in ("hfus", "ious", "oaus")] 
    the_file.seek(0)  # just to be sure you start from the beginning (but it should without this...)  
    the_file.writelines(lines_to_write)
    the_file.truncate()

有关打开模式,请参阅 open, modes

对于这种数据处理我建议使用pandas

import pandas as pd
df = pd.read_csv("033117.txt", header=None, names=['foo','bar','foobar','barfoo'])
df = df[df.foo.isin(['hfus','oaus'])]
df.to_csv("result.txt")

当然,您想使用更有意义的 header 值 ;-)

with open('033117.txt') as inFile, open('result.txt', 'w') as outFile:
    for line in inFile:
        if line.split()[0] in ('hfus', 'ious', 'oaus'):
            outFile.write(line)

尝试使用 with 语句而不是 outFile = open() 打开文件。这应该有助于减少错误 :)

with open('033117.txt') as inFile, open('result.txt', 'w') as outFile:
    for line in inFile:
        if line.split()[0] in ('hfus', 'ious', 'oaus'):
            outFile.write(line)