繁体   English   中英

Python的OS模块写入到给出“ TypeError”的文件中

[英]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”而引发该错误。 我觉得我忽略了一些琐碎的事情,尤其是这个脚本的简单程度……任何帮助将不胜感激! :)

如果要使用os.open ,则必须使用os标志来标识打开文件的模式:

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

您尝试打开文件的方式对于内置的open方法是正确的

祝好运 !

从您链接的文档中

如果您只想读取或写入文件,请参见open()

就像我在评论中说的,更改此:

os.open(...)

对此:

open(...)

引用此处提供的Python文档

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

正如其他人已经说过的那样,您应该使用内置的open函数。

暂无
暂无

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

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