1

I chose csv's specific column and converted it to txt.

The selected column name is 'id' (header) and I don't know how to remove that 'id' from txt.

This is my code..

import csv
with open('garosu_example.csv') as file:
    reader = csv.reader(file)

input_file = "garosu_example.csv"
output_file = "garosu_example.txt"

id = ['id']
selected_column_index = []

with open(input_file, 'r', newline='') as csv_in_file:
    with open(output_file, 'w', newline='/n') as csv_out_file:
        freader = csv.reader(csv_in_file)
        fwriter = csv.writer(csv_out_file)
        header = next(freader)
        for index_value in range(len(header)):
            if header[index_value] in id:
                selected_column_index.append(index_value)
        print(id)
        fwriter.writerow(id)
        for row_list in freader:
            row_list_output = []
            for index_value in selected_column_index:
                row_list_output.append(row_list[index_value])
            print(row_list_output)
            f.writer.writerow(row_list_output)

How can I remove 'id'(header) from txt file?

If I remove header in csv, output txt file is emptyT_T

Here is an example of my csv file

4
  • How does the csv file look like? Commented May 20, 2019 at 2:34
  • I edited my question. I have linked it's img. Commented May 20, 2019 at 2:39
  • Anyway, i answered already Commented May 20, 2019 at 2:39
  • If any of the answers solved your question, it's good practice to upvote them and accept the best one (I see you've already done this). The latter also grants you a small rep bonus :) Commented May 20, 2019 at 3:01

3 Answers 3

4

Another way with readlines and writelines:

with open('filename.csv') as f:
    with open('no_header.csv', 'w') as f2:
        f2.writelines(f2.readlines()[1:])
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

1

Another way you can try is to use pandas to manipulate your csv file.

An example of using pandas to manipulate the csv file would be

import pandas as pd

df = pd.read_csv("<Your-CSV-file>", columns=["id", "name", "longitude", "latitude"])
df.drop(columns=["id"])  ## this will drop the column named id
df.to_csv("<Your-New-CSV-file-Path>", index=None, header=True)

Hope it helps.

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.