When i try to create a new file it just returns error

Why this piece of code work:

open("txtfile/file.txt", "w").write("1234") 

On w3schools it has this

I believe it’s better to do something like this:

file = open("test.txt", "w")
file.write("Hello world!")

It’s usually good practice to close the file once you’re finished with it.

But when I test this in a new Python Repl:

open("test.txt", "w").write("Hello world!")

It does seem to work…

Could you maybe provide a link to the Repl that isn’t working so the community can help determine why it isn’t working?

i want to create a folder then create a file inside that folder @MattDESTROYER

1 Like

This should help you with making a folder. Essentially, you can use os.makedir or os.makedirs depending on the situation.

In a scenario where you had this path: /some/path/, and you wanted to create an extra folder, here in the path directory, you would use os.makedir:

import os

In a scenario where you had the same path and you wanted to create a folder with a subfolder, /in/here, inside of the path directory, you would use os.makedirs:

import os

This would result in an error if you attempted this with os.makedir as the path /some/path/in does not exist.

Also note, both functions will raise an error if the directory specified already exists, however with os.makedirs, this can be suprressed by adding the exist_ok parameter and setting it to true:

import os
os.makedirs("/some/path/that/already/exists", exist_ok = True);

(As far as I can tell, you cannot directly create a folder while/by creating a file in a directory that does not exist. This will simply result in an error as the directory doesn’t exists.)

1 Like

i tried the following code and it just return error

import os

it returned this error
link to my repl

1 Like

You need to include the os. (it’s also mkdir, not makedir, that’s my fault):


lol I am an idiot thanks @MattDESTROYER

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.