2012-12-27 194 views
4

只是想知道什麼是應該做這個..我有以下內容的文件最簡單的方法:蟒蛇:數列

01 04 
02 04 
04 04 

我打算修改我的文件追加「失蹤的文件,自04意味着有4項,但是3號丟失:

01 04 
02 04 
#missing 
04 04 

什麼是最簡單的方式,我敢肯定這是一個簡單的修復,只是我是新來的蟒蛇,我繼續努力?非常囉嗦的實施這個方法。

希望能從這裏聽到一些東西,謝謝大家!

+3

http://whathaveyoutried.com? – Fabian

回答

4
with open('path') as f: 
    for i, line in enumerate(f, start=1): 
     if int(line.split()[0]) == i: 
      pass 
     else: 
      #put missing 

我沒試過這段代碼。這只是概念。

+0

Thanks Dmitry :)當我嘗試使用時出現以下錯誤:Warning:'with'將成爲Python 2.6中的保留關鍵字 ,其中打開的(temp_file_path)爲f: ^ SyntaxError:無效的語法 – user1931765

0

使用另一個文件,然後用它替換你的文件。

text = file('file_name','r').read() // read from file 
list = '00 00' + [line for line in text] 
new_list = [] 
l=len(list) 
for i in xrange(1,l): 
    new_list+=['missing' for i in range(int(list[i].split()[0])-int(list[i-1].split()[0])+1)] 
    new_list.append(list[i]) 

然後寫new_list到文件,然後用這一個

0

替換文件試試這個:

f = open('file.txt', 'r') 
newfile = [] 
lines = f.readlines() 
number = lines[0][-3:-1] 
for i in range(int(number)): 
    string = '0' + str(i+1) + ' ' + number 
    if i + 1 != int(number): 
     string += '\n' 
    if string not in lines: 
     newfile.append('missing\n') 
    else: 
     newfile.append(string) 
f.close() 
f = open('file.txt', 'w') 
f.writelines(newfile) 
f.close() 

它工作時,我與你的榜樣嘗試。它檢查字符串是否在文件中,如果不是,則寫入'missing'

注意:不完全確定是否有讀寫模式(截斷)

+0

不一定是最短的方式,但它工作正常。 – Volatility