这里是我的脚本:Python的OS模块写入文件给予“类型错误”
import random
import os
i = 0
file = os.open("numbers.txt", "w")
while i < 5000:
ranNumb = str(random.randint(1,500))
file.write(ranNumb,",")
最终目标是简单地在它5000个随机生成的数字一个文本文件,我想在以后的项目中使用。当我运行这个小脚本,我得到以下错误:
Traceback (most recent call last):
File "C:/Users/LewTo002/Desktop/New folder (2)/numGen.py", line 5, in <module>
file = os.open("numbers.txt", "w")
TypeError: an integer is required (got type str)
我查看以下网站来解决自己的问题: http://learnpythonthehardway.org/book/ex16.html
https://docs.python.org/3/library/os.html
https://docs.python.org/3/tutorial/inputoutput.html
而且根据对于那些,我做的是正确的。根据我的IDE(使用JetBrain的PyCharm),该错误是由于“file = os.open('numbers.txt','w')”中的“w”引发的。我觉得我可以忽略一些微不足道的东西,特别是这个剧本的简单性......任何帮助都会得到彻底的赞赏! :)
尝试删除'os.open'的'os.'部分 - 'open'是一个内置函数! – Aurora0001
呃!这是它!谢谢:) –
...如果你想使用低级IO,你还需要'os.write()'。 'os.open()'返回一个简单的'int',即文件描述符号,它本身不具有方法。 – dhke