- 1 year ago
How to get the header from a CSV file and write it to another file?
You can use Python's built-in csv
module to read the header from a CSV file and then write it to another file. Here's a step-by-step guide to achieve this:
Suppose you have a CSV file named "input.csv," and you want to extract the header and write it to "output.csv."
pythonimport csv
# Function to read the header from the input CSV file
def read_csv_header(input_file):
with open(input_file, 'r', newline='') as csvfile:
reader = csv.reader(csvfile)
header = next(reader) # Read the first row as the header
return header
# Function to write the header to the output CSV file
def write_csv_header(output_file, header):
with open(output_file, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(header)
if __name__ == "__main__":
input_file = 'input.csv'
output_file = 'output.csv'
header = read_csv_header(input_file)
write_csv_header(output_file, header)
In this code:
The
read_csv_header
function reads the first row of the CSV file (the header) usingcsv.reader
andnext(reader)
. It returns the header as a list.The
write_csv_header
function takes the output CSV file name and the header list as input and writes the header to the output file usingcsv.writer
andwriter.writerow()
.In the
__main__
block, you specify the input and output file names. The code reads the header from the input file and then writes it to the output file.
When you run this Python script, it will read the header from "input.csv" and write it to "output.csv." The "output.csv" file will contain only the header row without any data.