Python : writing to a file

Dave Angel davea at davea.name
Sat Jan 10 10:37:55 EST 2015


On 01/10/2015 10:14 AM, Ganesh Pal wrote:
> Please provide you input on the below questions:
>

For each new thread, you should specify at a minimum your Python version 
and OS.  it frequently matters, and it's better to specify than to have 
everyone try to guess.  I'll assume Python 2.7 and Linux.

>
> (a) I was expecting  the string i.e day of week , example Saturday to be
> written in the file. what Iam I missing in the below program  ?
>
> Program:
>
> #!/usr/bin/python
>
> import time
> f = open ('test_2.txt','w+b')
> DAY = time.strftime("%A")
> f.write(DAY)
> f.close()
>
> Throttling-1# cat test_2.txt

Not to belabor the obvious, but did you run the program?  I'd add at 
least one print to a minimal program to make sure you ran the same 
program as you show, and you can also use that to inspect the contents 
of variables.

Works for me on ubuntu Python 2.7

Incidentally, I'd avoid using w+b.  Just use wb if you're creating a file.

>
> (b) Iam trying to generate a file in the below format ,
>
> cluster1# cat test_2.txt
>
> Saturday 0:05 0:10
> Saturday 0:10 0:20
> Saturday 0:20 0:30
> Saturday 0:40 0:50
> Saturday 0:60 0:70
>
> (a) what is the easiest way to generate the above file fprmat ?
>
> (b) how will I take care that the below format is repeated in the .txt file
>    ( i.e column and row spacing)
>
>      DAY OF THE WEEK  [SPACE] START TIME [ SPACE] ENDTIME{SPACE]
>
>
> (c) how do I  add START TIME [ SPACE] ENDTIME{SPACE] columns
>

The use the str.format method.

line = "{} {} {}\n".format(day, start, end)

The curlies specify where the various arguments will be placed, and the 
"\n" generates a newline at the end.

-- 
DaveA



More information about the Python-list mailing list