OK, so when I use open(<filename>, 'w') the program either writes to the specified file or creates a new one if it doesn't exist, right? Is there a way to create a folder path or something? Like to create D:\My Documents\Folder and create a file in that folder? How would I do that?

Recommended Answers

All 9 Replies

So how does it work exactly? you just use os.mkdir() or os.makedirs()?

Could you give me an example perhaps? Sorry for being kind of a noob, but it gave me a syntax error and I haven't actually ever seen this in action, so I don't really know what I'm doing.

os.makedirs is a really useful function. It makes all of the path that you give it. So if you gave it the path C:\Python\Test\one\two you dont already have to have the path Python, Test, one or two. This is better then os.mkdir because that doesn't work unless you have the full path except the one you want to create. So in that case you would need C:\Python\Test\one and two would be the one created.

import os

#Firstly we make the folder path.
os.makedirs("C:\Python\Storing\a\Text\File\)
#then we change the directory that python looks at to the new place.
os.chdir("C:\Python\Storing\a\Text\File)

#and because we changed the directory we can just go
f = open("File.txt",'w')
#rather then open("C:\Python\Storing\a\Text\File\file.txt",'w')

#write to the text file
f.write("Hello world")

#and close it
f.close()

Hope that helps

I want to know how to create a folder in python so i can save certain variables. Can anybody help me?

see documentation of 'os' module

Tanks for the code, i'm happy to see it, its all i need to complate my project thanks agin.

what is wrong with this code please
import os
os.makedirs("C:\Journal\")

I Keep getting EOL while scanning string literal

commented: You must use os.makedirs("C:\Journal") instead of the other one. +0

You can also use this method for checking a file:

from os import path, access, R_OK

PATH='file path'

if path.exists(PATH) and path.isfile(PATH) and access(PATH, R_OK):
    #do something

else:
    open(PATH,'w')

You must double the escape characters \ ie \\ or use raw strings by adding before quotes or use / instead of \. You can also buuld the path dynamically by os.path.join

Next time start your own thread, please!

commented: Hmm... Who are you talking to? +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.