Home > Mobile >  Set header of csv using separate text file
Set header of csv using separate text file

Time:10-30

I'm trying to read data from a textfile which consists of newline separated words I intend to use as the header for a separate csv file with no header.

I've loaded the textfile and dataset in via pandas but don't really know where to go from here.

names = pandas.read_csv('names.txt', header = None)
dataset = pandas.read_csv('dataset.csv, header = None')

The contents of the textfile look like this

dog
cat
sheep
...

CodePudding user response:

You could probably read your .txt file in a different way, such as using splitlines() (as you can see from this example)

with open('names.txt') as f:
    header_names = f.read().splitlines()

header_names is now a list, and you could it to define the header (column names) of your dataframe:

dataset = pandas.read_csv('dataset.csv', header = None)
dataset.columns = header_names
  • Related