![](/img/trans.png)
[英]Why python os module not giving me the correct file location of the file?
[英]Python's OS module to write to file giving “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
根据这些,我做得正确。 根据我的IDE(使用JetBrain的PyCharm),具体是由于“ file = os.open('numbers.txt','w')”中的“ w”而引发该错误。 我觉得我忽略了一些琐碎的事情,尤其是这个脚本的简单程度……任何帮助将不胜感激! :)
引用此处提供的Python文档
此功能适用于低级I / O。 为了正常使用,请使用内置函数open(),该函数将返回带有read()和write()方法(还有更多)的“文件对象”。 要将文件描述符包装在“文件对象”中,请使用fdopen()。
正如其他人已经说过的那样,您应该使用内置的open
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.