Python的OS模块写入文件给出" TypeError"

时间:2016-08-02 12:40:29

标签: python typeerror

这是我的剧本:

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

根据这些,我正在做正确的事。错误是由于&#34; w&#34;而特别引起的。 in&#34; file = os.open(&#39; numbers.txt&#39;,&#39; w&#39;)&#34;根据我的IDE(使用JetBrain&#39的PyCharm)。我觉得我忽略了一些微不足道的事情,特别是这个脚本有多么简单......任何帮助都会被彻底赞赏! :)

3 个答案:

答案 0 :(得分:2)

如果您想使用os.open,则必须使用os flags来确定要打开文件的模式:

file = os.open("numbers.txt", os.O_WRONLY)

您尝试打开文件的方式对built in open method

是正确的

祝你好运!

答案 1 :(得分:0)

来自你链接的documentation

  

如果您只想阅读或撰写文件,请参阅open()

正如我在评论中所说,改变这个:

os.open(...)

对此:

open(...)

答案 2 :(得分:0)

引用可用的Python文档here

  

此功能适用于低级I / O.对于正常使用,使用内置函数open(),它返回带有read()和write()方法的“文件对象”(以及更多)。要将文件描述符包装在“文件对象”中,请使用fdopen()。

您应该使用其他人已经说过的内置SELECT CAST([COLUMN] AS INT) + CASE WHEN [COLUMN] MOD 1 >= 0.5 THEN 1 ELSE 0 END from [table] results: 9.1 9 9.2 9 9.3 9 9.4 9 9.5 10 9.6 10 9.7 10 9.8 10 9.9 10 10 10 功能。