简体   繁体   English

python io.open()整数必需错误

[英]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. 据我了解,这是当有人无意中使用os.open()而不是io.open()时出现的一个问题,这就是我指定io选项的原因。 It should be noted that the same error comes up regardless if I import the os module. 应该注意的是,无论我是否导入os模块,都会出现相同的错误。

I'm using python 3.2.5 我正在使用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. f = io.open('%s',today,'w')行应具有'%s'第一个参数,第一个参数必须是文件名。 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”语句,这样在出现异常的情况下流将始终关闭,例如:

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

I hope I have been helpful. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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