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
Check If Values of Multiple Columns Are the Same (Python)
How to Merge Elements in List in Python With Condition
How to Install Pypdf2 Module Using Windows
How to Write Python Array (Data = []) to Excel
How to Cleanly Uninstall Ansible
Turn String into a List and Remove Carriage Returns (Python)
Python: How to Keep Repeating a Program Until a Specific Input Is Obtained
How to Locate the Index With in a Nested List Python
How to Create a for Loop That Goes Through All Diagonal Possibilities of a List
Python Overflowerror: Int Too Large to Convert to Float
How to Dynamically Build a Json Object
Cv2.Videocapture.Open() Always Returns False
Spliting a Row to Multiple Row Pyspark
How to Locate Elements on Webpage With Headless Chrome
Check If Dataframe Has a Zero Element