繁体   English   中英

根据第一列从文本文件中提取行到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()

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

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()

有关开放模式 ,请参见开放模式。

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)

试试这个查询:

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的新手,因此可能会有许多更好的解决方案,但这应该可以工作。

对于这种数据处理,我建议使用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")

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

尝试使用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)

暂无
暂无

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

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