Python Forum
In CSV, how to write the header after writing the body?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
In CSV, how to write the header after writing the body?
#6
You can do this:
class ChangeHeader:
    def __init__(self, file, newheader=None, newfile=None):
        self.file = file
        self.newfile = newfile
        self.nhead = newheader
        self.fix_header()

    def fix_header(self):
        addednew = False
        with open(self.file, 'r') as f, open(self.newfile, 'w') as f1:
            for line in f:
                if not addednew:
                    f1.write(self.nhead)
                    addednew = True
                else:
                    f1.write(line)

def testit():
    newhead = 'Product Name	PartDesc	Drawings	Issues	Documents'
    ChangeHeader(file='somedwgs.csv', newheader=newhead, newfile='somedwgs_new.csv')

if __name__ == '__main__':
    testit()
results:
Before:
   

after
   

Attached Files

.csv   somedwgs.csv (Size: 391 bytes / Downloads: 302)
Reply


Messages In This Thread
RE: In CSV, how to write the header after writing the body? - by Larz60+ - Jan-03-2018, 10:42 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [BeautifulSoup] Find </body>? Winfried 3 1,442 Jul-21-2023, 11:25 AM
Last Post: Gaurav_Kumar
  Get html body of URL rama27 6 3,569 Aug-03-2020, 02:37 PM
Last Post: snippsat
  malformed header from script 'main.py': Bad header: * Serving Flask app "main" anuragsapanbharat 2 4,596 Jun-12-2019, 07:26 AM
Last Post: anuragsapanbharat
  Is it possible to perform a PUT request by passing a req body instead of an ID ary 0 1,868 Feb-20-2019, 05:55 AM
Last Post: ary

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020