Python sequence: number

just wondering what is the easiest way to do this. I have a file with the following contents:

01 04 02 04 04 04 

I plan to edit the file to add "missing to the file, since 04 means there are 4 elements, but number 3 is missing:

 01 04 02 04 #missing 04 04 

What is the easiest way to do this? I am sure this is a simple fix, I'm just new to python, and I continue to have so many ways to implement this.

Hope to hear something from here, thanks everyone!

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

I have not tried this code. it is just a concept.

+4
source

Using a different file, then replace it with it.

 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]) 

then write new_list to the file, then replace the file with this

0
source

Try the following:

 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() 

This worked when I tried with your example. It checks to see if a line is in the file and writes 'missing' if not.

Note. Not quite sure if there is a read and write mode (truncated)

0
source

All Articles