How to Read a Column Without Header from CSV and Save the Output in a Txt File Using Python

How can I remove header from csv or txt file?

You can skip the first line and replace the document with everything after:

with open(file) as f:
with open("file_without_header.csv",'w') as nh:
next(f)
for l in f:
nh.write(l)

Set header of csv using separate text file

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

Is there a way of writing txt columns to a csv file?

From what I have understood, you need to read txt files and write the first column to a csv file. For your usecase, I wrote functions to read csv, extract first column, combine all of first columns of your data and write them to a csv file at the end. For that you need to specify filenames of your data files.

def read_csv(file_path):
with open(file_path, "r") as f:
lines = f.readlines()
return lines[1:len(lines)-1] #ignoring your first line and last line

def extract_first_column(file_path): #returns first column
lines = read_csv(file_path)
first_col = []
for elem in lines:
elem = elem.strip().split(" ")
if not elem == "":
first_col.append(elem[0])
return first_col

def combined_array(file_path_list): #combines all of columns to one array
all_values = []
for file_path in file_path_list:
col_data = extract_first_column(file_path)
all_values.append(col_data)
return all_values

def write_csv(array, csv_name, delim): #writes the array to a csv file
with open(csv_name,"w") as f:
for elem in array:
if not elem == "":
f.write(elem + delim)

file_name_list = ["data.txt"] #you specify all 7 filenames here
array = combined_array(file_name_list) #array containing all 7 columns
array = [x for sublist in array for x in sublist]
write_csv(array, "test.csv", "\n") #writing to csv file

This worked for me with the sample file you provided. I will update my answer if I misunderstood your request.



Related Topics



Leave a reply



Submit