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!
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With