簡體   English   中英

從txt文件中選取零件,然后使用python復制到另一個文件

[英]Pick parts from a txt file and copy to another file with python

我在這里遇到麻煩了。 我需要讀取一個文件。 包含一系列記錄的Txt文件,檢查我要將它們復制到新文件的記錄。 文件內容是這樣的(這只是一個示例,原始文件有3萬多行):

AAAAA|12|120 #begin file
00000|46|150 #begin register
03000|TO|460 
99999|35|436 #end register
00000|46|316 #begin register
03000|SP|467
99999|33|130 #end register
00000|46|778 #begin register
03000|TO|478
99999|33|457 #end register
ZZZZZ|15|111 #end file

以03000開頭且字符為“ TO”的記錄必須寫入新文件。 根據示例,文件應如下所示:

AAAAA|12|120 #begin file
00000|46|150 #begin register
03000|TO|460 
99999|35|436 #end register
00000|46|778 #begin register
03000|TO|478
99999|33|457 #end register
ZZZZZ|15|111 #end file

碼:

file = open("file.txt",'r')
newFile = open("newFile.txt","w")    
content = file.read()
file.close()
# here I need to check if the record exists 03000 characters 'TO', if it exists, copy the recordset 00000-99999 for the new file.

我進行了多次搜索,沒有發現任何幫助。 謝謝!

with open("file.txt",'r') as inFile, open("newFile.txt","w") as outFile:
    outFile.writelines(line for line in inFile 
                       if line.startswith("03000") and "TO" in line)

如果您需要上一行和下一行,那么您必須在三元組中迭代inFile 首先定義:

def gen_triad(lines, prev=None):
    after = current = next(lines)
    for after in lines:
        yield prev, current, after
        prev, current = current, after

然后像以前一樣做:

outFile.writelines(''.join(triad) for triad in gen_triad(inFile) 
                   if triad[1].startswith("03000") and "TO" in triad[1])
import re

pat = ('^00000\|\d+\|\d+.*\n'
       '^03000\|TO\|\d+.*\n'
       '^99999\|\d+\|\d+.*\n'
       '|'
       '^AAAAA\|\d+\|\d+.*\n'
       '|'
       '^ZZZZZ\|\d+\|\d+.*')
rag = re.compile(pat,re.MULTILINE)

with open('fifi.txt','r') as f,\
     open('newfifi.txt','w') as g:
    g.write(''.join(rag.findall(f.read())))

對於以00000、03000和99999開頭的行之間有其他行的文件,我發現沒有比這更簡單的代碼了:

import re

pat = ('(^00000\|\d+\|\d+.*\n'
       '(?:.*\n)+?'
       '^99999\|\d+\|\d+.*\n)'
       '|'
       '(^AAAAA\|\d+\|\d+.*\n'
       '|'
       '^ZZZZZ\|\d+\|\d+.*)')
rag = re.compile(pat,re.MULTILINE)

pit = ('^00000\|.+?^03000\|TO\|\d+.+?^99999\|')
rig = re.compile(pit,re.DOTALL|re.MULTILINE)

def yi(text):
    for g1,g2 in rag.findall(text):
        if g2:
            yield g2
        elif rig.match(g1):
            yield g1

with open('fifi.txt','r') as f,\
     open('newfifi.txt','w') as g:
    g.write(''.join(yi(f.read())))
file = open("file.txt",'r')
newFile = open("newFile.txt","w")    
content = file.readlines()
file.close()
newFile.writelines(filter(lambda x:x.startswith("03000") and "TO" in x,content))

這似乎有效。 其他答案似乎只是寫出包含“ 03000 | TO |”的記錄 但您也必須在此前后寫出記錄。

    import sys
# ---------------------------------------------------------------
# ---------------------------------------------------------------
# import file
file_name = sys.argv[1]
file_path = 'C:\\DATA_SAVE\\pick_parts\\' + file_name
file = open(file_path,"r")
# ---------------------------------------------------------------
# create output files
output_file_path = 'C:\\DATA_SAVE\\pick_parts\\' + file_name + '.out'
output_file = open(output_file_path,"w")
# create output files

# ---------------------------------------------------------------
# process file

temp = ''
temp_out = ''
good_write = False
bad_write = False
for line in file:
    if line[:5] == 'AAAAA':
        temp_out += line 
    elif line[:5] == 'ZZZZZ':
        temp_out += line
    elif good_write:
        temp += line
        temp_out += temp
        temp = ''
        good_write = False
    elif bad_write:
        bad_write = False
        temp = ''
    elif line[:5] == '03000':
        if line[6:8] != 'TO':
            temp = ''
            bad_write = True
        else:
            good_write = True
            temp += line
            temp_out += temp 
            temp = ''
    else:
        temp += line

output_file.write(temp_out)
output_file.close()
file.close()

輸出:

AAAAA|12|120 #begin file
00000|46|150 #begin register
03000|TO|460 
99999|35|436 #end register
00000|46|778 #begin register
03000|TO|478
99999|33|457 #end register
ZZZZZ|15|111 #end file

一定是python嗎? 這些shell命令在緊要關頭會做同樣的事情。

head -1 inputfile.txt > outputfile.txt
grep -C 1 "03000|TO" inputfile.txt >> outputfile.txt
tail -1 inputfile.txt >> outputfile.txt
# Whenever I have to parse text files I prefer to use regular expressions
# You can also customize the matching criteria if you want to
import re
what_is_being_searched = re.compile("^03000.*TO")

# don't use "file" as a variable name since it is (was?) a builtin 
# function 
with open("file.txt", "r") as source_file, open("newFile.txt", "w") as destination_file:
    for this_line in source_file:
        if what_is_being_searched.match(this_line):
            destination_file.write(this_line)

對於那些更喜歡緊湊的表示形式的人:

import re

with open("file.txt", "r") as source_file, open("newFile.txt", "w") as destination_file:
    destination_file.writelines(this_line for this_line in source_file 
                                if re.match("^03000.*TO", this_line))

碼:

fileName = '1'

fil = open(fileName,'r')

import string

##step 1: parse the file.

parsedFile = []

for i in fil:

    ##tuple1 = (1,2,3)    

    firstPipe = i.find('|')

    secondPipe = i.find('|',firstPipe+1)

    tuple1 = (i[:firstPipe],\
                i[firstPipe+1:secondPipe],\
                 i[secondPipe+1:i.find('\n')])

    parsedFile.append(tuple1)


fil.close()

##search criterias:

searchFirst = '03000'  
searchString = 'TO'  ##can be changed if and when required

##step 2: used the parsed contents to write the new file

filout = open('newFile','w')

stringToWrite = parsedFile[0][0] + '|' + parsedFile[0][1] + '|' + parsedFile[0][2] + '\n'

filout.write(stringToWrite)  ##to write the first entry

for i in range(1,len(parsedFile)):

    if parsedFile[i][1] == searchString and parsedFile[i][0] == searchFirst:

        for j in range(-1,2,1):

            stringToWrite = parsedFile[i+j][0] + '|' + parsedFile[i+j][1] + '|' + parsedFile[i+j][2] + '\n'

            filout.write(stringToWrite)


stringToWrite = parsedFile[-1][0] + '|' + parsedFile[-1][1] + '|' + parsedFile[-1][2] + '\n'

filout.write(stringToWrite)  ##to write the first entry

filout.close()

我知道這個解決方案可能會有點長。 但這很容易理解。 這似乎是一種直觀的方法。 而且我已經使用您提供的數據進行了檢查,它可以完美運行。

如果您需要有關代碼的更多說明,請告訴我。 我一定會添加相同的內容。

我給(Beasley和Joran elyase)小費很有趣,但它只允許獲取03000行的內容。我想將00000行的內容獲取到99999行。我什至設法在這里做,但我不是滿意,我想做一個更清潔的。 看看我是怎么做的:

    file = open(url,'r')
    newFile = open("newFile.txt",'w')
    lines = file.readlines()        
    file.close()
    i = 0
    lineTemp = []
    for line in lines:                     
        lineTemp.append(line)                       
        if line[0:5] == '03000':
            state = line[21:23]                                
        if line[0:5] == '99999':
            if state == 'TO':
                newFile.writelines(lineTemp)                    
            else:
                linhaTemp = []                                                                            
        i = i+1                      
    newFile.close()

建議...謝謝大家!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM