Coeus2016
Coeus2016

Reputation: 355

How may I write Python file at run time?

I want to create multiple text files in Python. These files will be created as the code runs. I was thinking to use

fn = date.today().isoformat() + ".log"

or

>>> from datetime import date
>>> fn=ctime()+".txt"
>>> print fn
Thu Feb 18 22:21:35 2016.txt

so that I can get unique file names always. But experiment seems not going very fine, as I want to insert data in them dynamically, as it may come from any external source. There are some silly errors happening like follows,

>>> fn = date.today().isoformat() + ".log"
>>> print fn
2016-02-18.log
>>> quit()
>>> fp = open( fn, "w" )
>>> fp.write( "data" )
>>> fp.close()
>>> fr=open(fp,"r")

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    fr=open(fp,"r")
TypeError: coercing to Unicode: need string or buffer, file found

or

>>> fn=ctime()+".txt"
>>> print fn
Thu Feb 18 22:21:35 2016.txt
>>> line1="unanimous resolution to this effect"
>>> fp = open( fn, "w" )

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    fp = open( fn, "w" )
IOError: [Errno 22] invalid mode ('w') or filename: 'Thu Feb 18 22:21:35 2016.txt' 

I am getting stuck. But my sense is telling I may be doing some interesting error. If anyone may kindly suggest how may I address the problem or resolve the errors to solve the problem. Thanks in advance. I am using Python2.7.11 on Windows 10.

Upvotes: 1

Views: 410

Answers (3)

Pistis Valentino
Pistis Valentino

Reputation: 143

use:

fr=open(fp.name,"r")

instead of:

fr = open( fp, "r" )

Upvotes: 0

KarolisR
KarolisR

Reputation: 626

You can't have ":" in file name, use this:

import datetime
fn = datetime.datetime.now().strftime("%Y-%m-%d %H%M%S") + ".log"
print fn

gives:

2016-02-18 174710.log

Upvotes: 0

Thomas Lotze
Thomas Lotze

Reputation: 5313

The first of your errors is probably just due to a typo, you should open the readable file by file name fn, not fp (which is a file object, not a string).

The second error appears to be due to file-name restrictions of Windows, it doesn't occur in a Linux environment.

Upvotes: 4

Related Questions