[Tutor] creating files

Kent Johnson kent37 at tds.net
Mon Nov 22 12:04:29 CET 2004


Liam Clarke wrote:
>>I'm sure there is a more elegant way of doing it since I am a non-programmer
>>beginner trying to learn Python for the first time.
> 
> If you're using Windows or DOS - 
> 
> You could simply do - 
> 
> dirPath = raw_input(" Please enter directory to save to: (in format
> c:\dave\ha\)")
> fileName = raw_input("Please enter filename : ")
> 
> dirPath = dirPath.replace("\","/")

You don't have to do this. Python works with both / and \ path 
separators on Windows.

Side note: If you are putting a directory path in a string you have to 
be careful with \ because it is the string escape character so you have 
to use double \\ or raw strings:
dirPath = "C:\\dave\\ha\\"
or
dirPath = r"C:\dave\ha\"

> if  not dirPath.endswith("/") :
>         filePath=dirPath+"/"+fileName
> else:
>         filePath=dirPath+fileName

These four lines can be replaced with
filePath = os.path.join(dirPath, fileName)

os.path.join() is smart enough to work with and without a trailing path 
separator on dirPath.

> 
> saveFile = (filePath, "w")
> 
> 
> 
> Raw input is the key. Please note that the above is very awkward, and
> Windows specific.
> ( Because os.path.join does funny stuff using 'current directories',
> which I don't understand )

I didn't know what you meant by this, I had to look at the docs. It 
turns out that what I said about os.path.join() adding path separators 
is not quite the whole story. If the first argument is just a drive 
letter, then it will not put in a separator, giving a relative path. If 
the first component is more than just a drive letter, it will put in a 
separator. For example,

 >>> import os
 >>> os.path.join('c:', 'foo')
'c:foo'
 >>> os.path.join('c:/', 'foo')
'c:/foo'
 >>> os.path.join('c:/bar', 'foo')
'c:/bar\\foo'

So in this case (where the user is typing in the directory) maybe Liam's 
code to concatenate the file path is the best solution.

Kent


More information about the Tutor mailing list