1

All,

This is a snippet of a text file that I need to change into a csv file.

|head1|head2|head3|
+----+------+-----+
|10000|10001|10002|

So I've used this python code to make it into a CSV.

#open the input & output files.
inputfile = open('tr2796h_05.10.txt', 'rb')
csv_file = r"mycsv1.csv"
out_csvfile = open(csv_file, 'wb')

#read in the correct lines
my_text = inputfile.readlines()[63:-8]
#convert to csv using | as delimiter
in_txt = csv.reader(my_text, delimiter = '|')
#hook csv writer to output file
out_csv = csv.writer(out_csvfile)
#write the data
out_csv.writerows(in_txt)
#close up
inputfile.close()
out_csvfile.close()

The output is this:

,head1,head2,head3,
,+----+------+-----+,
,10000,10001,10002,

as expected.

Question is this - how do I delete that second row?

2 Answers 2

2

Write the headers, skip a row, and then write the remaining rows.

out_csv.writerow(next(in_txt)) # headers
next(in_text) # skip
out_csv.writerows(in_txt) # write remaining
Sign up to request clarification or add additional context in comments.

4 Comments

I believe you transcribed my first line incorrectly. Note that it is writerow not writerows.
You were spot on. Is this or Lonut Hulub's method below the 'preferred' way of doing things? Could you help me understand the benefits of either?
@TangoAlee. Ionut Hulub's answer is spot on for your situation. My answer will work even in situations where you don't prefetch the data.
I want to accept both answers but can't apparently. I've accepted yours!
1

Add del my_text[1] after my_text = inputfile.readlines()[63:-8].

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.