在Python中基于第一列从文本文件提取行到文本

2024-06-16 09:48:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是Windows7.0,安装了Python3.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()

Tags: 文件txttruecloseifbufferlineopen
3条回答

我建议在打开文件对象时使用^{}语句,这样就不需要显式关闭文件,当缩进块退出时,它将自动关闭。
通过使用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。你知道吗

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

相关问题 更多 >