Todd Lewden Todd Lewden - 4 months ago 8
Python Question

Python's OS module to write to file giving "TypeError"

Here is my script:

import random
import os

i = 0
file = os.open("numbers.txt", "w")
while i < 5000:
ranNumb = str(random.randint(1,500))
file.write(ranNumb,",")


The end goal is simply a text file with 5000 randomly generated numbers in it that I would like to use in subsequent projects. When I run this little script I get the following error :

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)


I've reviewed the following sites to solve the problem myself :
http://learnpythonthehardway.org/book/ex16.html

https://docs.python.org/3/library/os.html

https://docs.python.org/3/tutorial/inputoutput.html

And according to those, I am doing the correctly. The error is thrown specifically due to the "w" in "file = os.open('numbers.txt', 'w')" according to my IDE ( using JetBrain's PyCharm ). I feel like I am overlooking something trivial especially with how simple this script is... Any assistance would be thoroughly appreciated! :)

Answer

If you want to use os.open you have to use os flags to identify mode in which you are going to open file:

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

The way you are trying to open file is correct for built in open method

Good Luck !