[Beginner] - Hanging in the code, can't figure out what's wrong

BartC bc at freeuk.com
Sun Apr 3 11:11:36 EDT 2016


On 03/04/2016 15:41, Loop.IO wrote:
> On Sunday, April 3, 2016 at 1:12:23 AM UTC+1, BartC wrote:
>> On 02/04/2016 23:31, Loop.IO wrote:
>>
>>> Oh i see, so the code prompts for a name.. so i'm more lost than i thought, what do I need to change to make it just create the file with the chosen name Launch2.bat without the prompt?
>>
>> If you don't want the user to enter anything, then I explained how
>> before, just use:
>>
>>        name='C:\\Documents\\PythonCoding\\launch2.bat'
>>
>> if that's the file name you need.
>>
>> --
>> Bartc
>
> Hi Bartc, i tried that, didn't work

You mean it gave an error when you tried to create that file?

Does that path already exist on your machine? If not then trying to 
create a file in a non-existent path won't work.

You can create the path manually outside of Python. Or look up the docs 
to find out how to do that. A quick google suggested using os.makedirs 
(to create multiple nested paths at the same time).

The following code worked on my machine:

import sys
import os

def create():
	print("creating new file")

	path="c:/Documents/PythonCoding/"
	name=path+"launch2.bat"

	try:
		os.stat(path)
	except:
		os.makedirs(path)

	print (name)

	try:
		file=open(name,'w')
		file.close()
	except:
		print("error occured")
		sys.exit(0)

create()

-- 
Bartc





More information about the Python-list mailing list