【问题标题】:Extracting lines from a text file based on first column to text in Python基于第一列从文本文件中提取行到Python中的文本
【发布时间】:2017-02-20 23:48:46
【问题描述】:

我使用的是 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()

【问题讨论】:

  • 在循环中,尝试beginning_line = line.split()[0],然后您可以使用if 'oaus' in beginning_line...进行检查。另外我建议使用with打开文件
  • if line.split()[0] in ('hfus', 'ious', 'oaus'): #do stuff

标签: python python-3.x parsing slice


【解决方案1】:

我建议您在打开文件对象时使用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 了解打开模式。

【讨论】:

  • 您的第一个示例正在运行,但覆盖示例却没有。 中的文件“read.py”,第 3 行 begin_line = line.split()[0] NameError: name 'line' is not defined PS I:\py>
  • 已修复。列表理解示例现在可以使用。特别是我测试了第二个 sn-p 来覆盖文件,它给了我你期望的输出文件。我建议使用它们,因为它们很简洁。
  • 我无法确定您说的是哪个 sn-p。我尝试了所有这些并且得到了不同的错误。如果不在一个街区内,我想我不会把它们拼凑在一起。
  • 希望现在很清楚,我删除了一些东西。我可以毫无问题地运行。第一个 sn-p 用于打开文件进行读取、选择适当的行并写入不同的输出文件。第二个 sn-p 是如果你想用选定的行覆盖同一个文件。
  • 我总是收到第二个错误 NameError: name 'file' is not defined
【解决方案2】:
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)

【讨论】:

    【解决方案3】:

    试试这个查询:

    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 新手,所以可能有很多更好的解决方案,但这应该可行。

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:

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

        【讨论】:

        • 这确实有效,但我的真正目标是覆盖原始文件。
        猜你喜欢
        • 1970-01-01
        • 2020-12-20
        • 1970-01-01
        • 1970-01-01
        • 2014-10-18
        • 1970-01-01
        • 2014-11-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多