簡體   English   中英

在 Python 中使用 readlines() function 檢查下一行的條件

[英]Check condition on upcoming line using readlines() function in Python

我有input.txt文件和output.txt文件,它們在 Python 腳本的參數中傳遞。 我正在使用readline() function 讀取輸入文件內容。在我更新到當前行並將其寫入 output 文件之前,我想檢查后續行的某些情況,如下所述。 你能給我一些指導嗎? 謝謝你。

如果行以01065008並滿足以下條件,我想從第 11 個位置使用internal_account值(16 位隨機數)更新當前行。

  1. 第 5 行從06開始,
  2. 06開頭的行從第 6 個字符開始的值為USD

輸入.txt

01065008200520P629658405456454
02BRYAN ANGUS      56425555643
0300000000000000000HUTS7858863
04PROSPECTUS ENCLOSYUSS574U623
05AS OF 05/13/20   45452366753
06Q47USDTFT        87845566765

input.txt文件有模式:

1st line will start with 010065008
2nd line will start with 02
...
6th line will start with 06
1st line will start with 010065008
...

我試過什么?

import random
import sys

infile=open(sys.argv[1], 'r')
lines=infile.readlines()

outfile=open(sys.argv[2], 'w')
internal_account = random.randint(1000000000000000,9999999999999999)

formattedStr = ''

for line in lines:
    if line[0:8] == '01065008':
        formattedStr='%s%s%s'%(line[0:10],internal_account,line[26:])
        outfile.write(formattedStr)
    else:
         outfile.write(line)
outfile.close()

要在文本文件中向前檢查,請將所有行讀入列表,然后使用行索引來向前檢查行。 使用enumerate function 來跟蹤線路索引。

ss = '''
01065008200520P629658405456454
02BRYAN ANGUS      56425555643
0300000000000000000HUTS7858863
04PROSPECTUS ENCLOSYUSS574U623
05AS OF 05/13/20   45452366753
06Q47USDTFT        87845566765
'''.strip()
with open ('input.txt','w') as f: f.write(ss)  # write data file

###############################3

import random
import sys

infile=open('input.txt')   #open(sys.argv[1], 'r')
lines=infile.readlines()

outfile=open('output.txt','w')  #open(sys.argv[2], 'w')

internal_account = random.randint(1000000000000000,9999999999999999)
print('internal_account', internal_account, end='\n\n')

formattedStr = ''

for i,line in enumerate(lines):
    line
    if line[0:8] == '01065008' and i < len(lines)-5 and lines[i+5].startswith('06') and lines[i+5][5:8] == 'USD':
        formattedStr='%s%s%s'%(line[0:10],internal_account,line[26:])
        outfile.write(formattedStr)
        print(formattedStr.strip())
    else:
         outfile.write(line)
         print(line.strip())
outfile.close()

Output

internal_account 2371299802657810

010650082023712998026578106454
02BRYAN ANGUS      56425555643
0300000000000000000HUTS7858863
04PROSPECTUS ENCLOSYUSS574U623
05AS OF 05/13/20   45452366753
06Q47USDTFT        87845566765

你離找到一個好的解決方案不遠了。 在輸入行上使用枚舉讓我們使用索引來檢查未來的行,以便您可以驗證是否滿足所有條件。 您需要捕獲IndexError以便在剩余行數不足時不會引發異常。

我對您的代碼所做的其他小修改:

  • 使用with語句來處理文件打開,以防止必須自己關閉文件。
  • 盡可能使用startswith使代碼更清晰。
  • 盡可能使用科學計數法使代碼更清晰。
import random
import sys

input_file, output_file = sys.argv[0:2]
internal_account = random.randint(1e15, 9999999999999999)

with open(input_file, "r") as stream:
    input_lines = stream.readlines()

with open(output_file, "w") as stream:
    for index, line in enumerate(input_lines):
        try:
            update_account = (
                line.startswith("01065008")
                and input_lines[index + 5].startswith("06")
                and input_lines[index + 5][5:8] == "USD"
            )
        except IndexError:
            update_account = False

        if update_account:
            line = line[0:10] + str(internal_account) + line[26:]

        stream.write(line)

暫無
暫無

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

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