Search code examples
pythonfilepython-2.7stringio

Appending files to each other without adding the title row each time


Bonjour Stack0verflow

I am trying to get this code to write the data to stored_output without line 1 (title line)

What I have tried:

with open(filenamex, 'rb') as currentx:
    current_data = currentx.read()
    ## because of my filesize I dont want to go through each line the the route shown below to remove the first line (title row)
    for counter, line in enumerate(current_data):
        if counter != 0:
            data.writeline(line)
    #stored_output.writelines(current_data)

Because of the filesize I dont want to do a for loop (efficiency)

Any constructive comments or code snippets would be appreciated.
Thanks AEA


Solution

  • You can use next() on the file iterator to skip the first line and then write rest of the content using file.writelines:

    with open(filenamex, 'rb') as currentx, open('foobar', 'w') as data:
        next(currentx)            #drop the first line
        data.writelines(currentx) #write rest of the content to `data`
    

    Note: Don't use file.read() if you want to read a file line by line, simply iterate over the file object to get one line at a time.