0

I tried many ways/combinations to insert headers (I need to add two column headers) but the file doesn't accept headers at file creation. At best, I get headers as rows come into the file one after the other. I can't see how to enter the headers only once persistently. Can you see in the code below where I could make some change please? Thanks.

            with open(MYFILE, "w", newline='') as csvWriter, open('read.csv', 'r', newline='') as csvReader:
            if keyword != "q":
                fieldnames = [engine, keyword]
                #fieldnames = ['Engine', 'Keywords']
                # writer = csv.DictWriter(csvWriter, fieldnames=[engine, keyword], extrasaction='ignore')
                writer = csv.DictWriter(csvWriter, fieldnames=fieldnames)
                writer.writeheader()

                reader = csv.DictReader(csvReader, fieldnames=fieldnames)
                writer.writerow({"Engine": engine, "Keywords": keyword})
                writer.writerows(reader)

I'm trying to save data into a csv file. I have two columns but no headers currently. I'd need some column titles like in any spreadsheet basically.

UPDATE ============================================== I've tried to insert to no avail the first block hereafter before and after the 2nd one. There is certainly something I'm not doing right but I don't know. Any suggestion, please?

STATUS = "quit"
print("Press [q] to quit at any time")
menu_engine = {}
menu_engine['1'] = "Google Search - Large Results"
menu_engine['2'] = "Google Search - Small Results"
menu_engine['3'] = "Yahoo Search - Large Results"
menu_engine['4'] = "Yahoo Search - Small Results"

while True:
options = menu_engine.keys()
for entry in options:
    print(entry, menu_engine[entry])
engine = input("Enter your Type of Search: ")

while STATUS != "q":
    keyword = input("Enter keyword(s): ")

    with open(MYFILE, "a", newline='') as csvWriter:
        if keyword != "q":
            fieldnames = [engine, keyword]
            writer = csv.DictWriter(csvWriter, fieldnames=fieldnames, extrasaction='ignore')
            writer.writeheader()

THE EXPECTED OUTPUT in the CSV File:

    Engine Number,Keywords
    4,man man
    4,mate mate
3
  • what are you trying to acheive here? Commented Dec 16, 2019 at 17:48
  • @Chris Doyle. I edited my post. See at the bottom of it. Thanks. Commented Dec 16, 2019 at 17:59
  • Can you add sample of the file content and sample expected output Commented Dec 17, 2019 at 0:46

2 Answers 2

1

you write the header with writeheader() then you can just write the rows

import csv
with open('new.dat', "w", newline='') as csvWriter, open('test.dat', 'r', newline='') as csvReader:
        fieldnames = ['Engine', 'Keywords']
        writer = csv.DictWriter(csvWriter, fieldnames=fieldnames)
        reader = csv.DictReader(csvReader, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(reader)

INPUT FILE

sef,56
sfd,67
eryt,67
sdfsf,34

OUTPUT FILE

Engine,Keywords
sef,56
sfd,67
eryt,67
sdfsf,34

UPDATE

I felt there should be an easier way to do this and seems you can use fileinput module from the standard python library to edit the same file inplace and insert the record at the start. this will save you having to the move or rename files.

import fileinput
headers = ['Engine','Type']
with fileinput.input('test.dat', inplace=1) as my_file:
    for line in my_file:
        if my_file.isfirstline():
            print(",".join(headers))
        print(line, end='')
Sign up to request clarification or add additional context in comments.

6 Comments

I'm on it. Cheers. I need to make sure I copy 'new.dat' to the 'test.dat' name. I'll use test.csv as I'm on Linux.
i feel there must be an easier way than this though as this seems a lot or work just to add a line at the start
updated the answer with a way to edit the file inplace and add in the line at the start
Is the test.dat extension supposed to do something that Linux cannot do or can it just be replaced with a test.csv file?
The extention makes no difference. I just call my test file test.dat as I use the same file to test lots of different data. So feel free to use .csv extention
|
0

Try:

df["new_column"]=" "
df.to_csv("your_file.csv", index= False)
print(df)      #to see if it's what you need

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.