Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a text file with no any delimiter in python?

I wish to write a simple text file with 6 lines in Python 2.7. I'm using this code:

import csv
export=open('./images2/test.tfw', "wb")
writer=csv.writer(export, delimiter=' ', quoting=csv.QUOTE_NONE)
writer.writerow('0.06')
writer.writerow('0.00')
writer.writerow('0.00')
writer.writerow('-0.06')
writer.writerow('-10.59')
writer.writerow('38.49')
export.close()

And I'm getting inside the file:

0 . 0 6
0 . 0 0
0 . 0 0
- 0 . 0 6
- 1 0 . 5 9
3 8 . 4 9

But I don't want spaces or anything else inside the numbers, I need simply this:

0.06
0.00
0.00
-0.06
-10.59
38.49

But when I try delimiter='' or delimiter=None, I get the error "delimiter must be set". How can I write my numbers without delimiters? Maybe it is a very basic question but I can't find it in google. Thank you!

like image 738
nadya Avatar asked Dec 07 '22 03:12

nadya


1 Answers

writerow expects an iterable, each element of which will be written to the file, separated by the delimiter. Hence when you give it a string (which itself is an iterable), it writes each character to the file, separated by the delimiter.
What you want to do instead, is to supply the "row" as a list of strings. In your case, each row has only one string, so supply each row as a list with only one string.

The CSV format requires a delimiter of some sort. Classically, this delimiter is the comma - hence the name (CSV = Comma Separated Values). However, should you feel the need to use a different delimiter, you could of course do so (typical choices include space, tab, hyphens, etc)

import csv
export=open('./images2/test.tfw', "wb")
writer=csv.writer(export, delimiter=',', quoting=csv.QUOTE_NONE)
writer.writerow(['0.06'])
writer.writerow(['0.00'])
writer.writerow(['0.00'])
writer.writerow(['-0.06'])
writer.writerow(['-10.59'])
writer.writerow(['38.49'])
export.close()
like image 83
inspectorG4dget Avatar answered Dec 30 '22 12:12

inspectorG4dget