简体   繁体   中英

python io.open() integer required error

I'm getting the following error when attempting to open a new file with today's date.

Traceback (most recent call last):
File "C:\BenPi\stacking\pi3\red_RTS\iotest.py", line 6, in <module>
f = io.open('%s',today, 'w')
TypeError: an integer is required

Here is my code

import datetime
import io
import os
today = datetime.date.today().strftime('%m_%d_%Y')
print (today)
f = io.open('%s',today, 'w')
f.write('first line \n')
f.write('second line \n')
f.close()

It is my understanding that this is an issue that arises when someone inadvertently uses os.open() instead of io.open() , which is why I specified the io option. It should be noted that the same error comes up regardless if I import the os module.

I'm using python 3.2.5

Thoughts?

You're not formatting correctly, you're using , instead of % :

f = io.open('%s'%today, 'w')

Besides, you can just do:

f = io.open(today, 'w')

The line f = io.open('%s',today, 'w') should have '%s' first argument the first argument must be the file name. If you write it like:

f = io.open(today, 'w')

Just works. Also consider using the "with" statment so in case of an exception the stream will be close anyway such as:

with io.open(today, 'w') as f:
    f.write("hello world")

I hope I have been helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM