0

I have a task to delete first 4 lines in 700 files. I wrote a script which deletes first 4 lines and copy modified file to a new directory. When I compared 2 files i.e. original and new one I noticed that it deleted first 4 lines and last 4 lines. This was not my goal, i.e. all lines should be the same except first 4 lines. Do you have an idea why it truncates last 4 lines and how to fix it? Thanks:

fileList = os.listdir(sys.argv[1])

    for file in fileList:
        absFile = os.path.join(os.path.abspath( sys.argv[1]), file )
        fileName = file
        FILE2 = open( fileName, 'w' )
        with open( absFile, 'r' ) as FILE:
            FileLines = FILE.readlines() 
            for line in FileLines:
                nline = line.rstrip()
                if FileLines.index(line) < 4:
                    continue
                else:
                    FILE2.write(line)
            shutil. copy( fileName, sys.argv[2] )

        FILE2.close()
        os.remove( fileName )

if __name__ == '__main__':
    main()
susja
  • 311
  • 3
  • 12
  • 33
  • 1
    Use some print statements inside the nested `for`, so you figure out what is happening. – Christian Tapia Mar 26 '14 at 03:10
  • 1
    Use some hints from here: http://stackoverflow.com/questions/9578580/skip-first-couple-of-lines-while-reading-lines-in-python-file – Esparta Palma Mar 26 '14 at 03:11
  • thanks, I tried both suggestions: second one didn't make a difference, when I tried first one i.e. put print line before FILE2.write(line) it printed all lines and did not truncated last 4 lines. Well it looks that something is wrong with writing to FILE2 ... still not clear – susja Mar 26 '14 at 03:36
  • I find the point of the issue: if I remove the line fileName = file it works fine. I just did it because I wanted to have the same name of the new file as original one. Otherwise the name of the file is whatever I provide when 'open' it. Need to figure out how to fix it – susja Mar 26 '14 at 03:54

1 Answers1

0

It's not a problem any more for me. The reason for failure in this case was poor design of the function. I fixed it. Ticket could be closed.

susja
  • 311
  • 3
  • 12
  • 33