Todd Lewden Todd Lewden - 1 year ago 43
Python Question

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

Here is my script:

import random
import os

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

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)/", line 5, in <module>
file ="numbers.txt", "w")
TypeError: an integer is required (got type str)

I've reviewed the following sites to solve the problem myself :

And according to those, I am doing the correctly. The error is thrown specifically due to the "w" in "file ='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 Source

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

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

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

Good Luck !