2

I am a beginner, writing a python script in which I need it to create a file that I can write information to. However, I am having problems getting it to create a new, not previously existing file.

for example, I have:

file = open(coordinates.kml, 'w') 

which it proceeds to tell me:

nameerror: name 'coordinates' is not defined. 

Of course it isn't defined, I'm trying to make that file. Everything I read on creating a new file says to take this route, but it simply will not allow me. What am I doing wrong?

I even tried to flat out define it...

file = coordinates.kml file_open = open(file, 'w') 

... and essentially got the same result.

3 Answers 3

6

You need to pass coordinates.kml as a string, so place them in quotes (single or double is fine).

file = open("coordinates.kml", "w") 
Sign up to request clarification or add additional context in comments.

1 Comment

It will create a file in the directory where the script was called, not where the script file is physically. Unless an absolute path is passed. In the latter case it will create the file at that particular position
0

In addition to the above answer, If you want to create a file in the same path, then no problem or else you need to specify the path as well in the quotes. But surely opening a file with read permission will throw an error as you are trying to access an nonexistent file.

Comments

0

To be future proof and independent of the platforms you can read and write files in binaries. For example if this is Python on Windows, there could be some alternations done to the end of line. Hence reading and writing in Binary mode should help, using switches "rb" and "wb"

file = open("coordinates.kml", "wb") 

And also remember to close the file session, else can throw errors while re running the script.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.