4

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

01 04 
02 04 
04 04

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

01 04 
02 04
#missing 
04 04

What is the easiest way to do this? I am pretty sure it's a simple fix, just that I am new to python and I keep trying very long-winded ways to implement this.

Hope to hear something from here, thanks everyone!

0

3 Answers 3

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

i did't try this code. it's just concept.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Dmitry :) I get this error when I try out: Warning: 'with' will become a reserved keyword in Python 2.6 with open(temp_file_path) as f: ^ SyntaxError: invalid syntax
0

Using another file and then replace your file 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 a file then replace your file with this one

Comments

0

Try this:

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

It worked when I tried with your example. It checks if a string is in the file, and writes 'missing' if not.

Note: Not entirely sure if there is a mode for reading and writing (with truncating)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.