2013-01-02 264 views
1

虛線,如果我有一個文本文件是這樣的:閱讀從文本文件

[001]This is line 1. 
[002][too long]This is line 2 but it's Tooooo 
oooo long! 
[003]This is line 3. 

我寫了「爲的fileA線」來讀取這個文件,如:

for line in fileA: 
    ... 

現在我當line.find(「[too long]」)> = 0時,需要合併當前行和下一行。 我該怎麼辦?

PS: 我寫道:

for line in fileA: 
    if line.find("[too long]")>=0: 
     loc = fileA.tell() 
     fileB = open("file.txt") #open this file again 
     fileB.seek(loc) 
     line += fileB.readline().strip() 

,但沒有奏效。爲什麼?

+0

您無法打開同一個文件,請張貼錯誤信息/堆棧跟蹤,究竟是什麼'didnt的工作?你不清楚你正在做什麼,這是阻礙我們的幫助。 –

+1

迭代遍歷行,維護一個緩衝區。當一行以'[...]開頭時,產生並清除緩衝區的內容,然後追加新的內容。當一行不以'[...]開始時,將其追加到緩衝區。 – katrielalex

回答

3

額外讀取文件時聲音太大。試試這個:

with open('file.txt') as f: 
    for line in f: 
     if '[too long]' in line: 
      line = line.rstrip('\r\n') + next(f) 
     print line 

打印

[001]This is line 1. 

[002][too long]This is line 2 but it's Tooooooooo long! 

[003]This is line 3. 

如果[too long]以線發現此附加以下行。也許你想追加所有更多的行,直到以[xxx]之類的內容開頭的行?

0

我不知道實際的文件看起來的樣子,但我可能會用的東西去像this

contents = """[001]This is line 1. 
[002][too long]This is line 2 but it's Tooooo 
oooo long! 
[003]This is line 3. 
""" 

lines = iter(contents.split("\n")) 

def fix_file(lines): 
    prev = '' 
    number = 1 
    for line in lines: 
     if not line.startswith('[{0:03d}]'.format(number)): 
      prev += line 
     else: 
      yield prev 
      number = number + 1 
      prev = line 
    yield prev 

for line in fix_file(lines): 
    print line 

這樣,你不需要額外的行內容。

2

您可以使用列表理解來獲取列表中的所有行,並執行與eumiros答案非常相似的操作。

with open('file.txt') as f: 
    lines = [line.rstrip('\r\n') + next(f) if '[too long]' in line else line for line in f] 

然後輸出爲:

>>> lines 
    ['[001]This is line 1.\n', "[002][too long]This is line 2 but it's Tooooooooo long!\n", '[003]This is line 3.\n']