LimeatronJamesIII
LimeatronJamesIII

Reputation: 15

Python3:Save File to Specified Location

I have a rather simple program that writes HTML code ready for use.

It works fine, except that if one were to run the program from the Python command line, as is the default, the HTML file that is created is created where python.exe is, not where the program I wrote is. And that's a problem.

Do you know a way of getting the .write() function to write a file to a specific location on the disc (e.g. C:\Users\User\Desktop)?

Extra cool-points if you know how to open a file browser window.

Upvotes: 0

Views: 3315

Answers (2)

Terrel Shumway
Terrel Shumway

Reputation: 464

The first problem is probably that you are not including the full path when you open the file for writing. For details on opening a web browser, read this fine manual.

import os
target_dir = r"C:\full\path\to\where\you\want\it"

fullname = os.path.join(target_dir,filename)
with open(fullname,"w") as f:
   f.write("<html>....</html>")

import webbrowser

url = "file://"+fullname.replace("\\","/")
webbrowser.open(url,True,True)

BTW: the code is the same in python 2.6.

Upvotes: 1

Dolda2000
Dolda2000

Reputation: 25855

I'll admit I don't know Python 3, so I may be wrong, but in Python 2, you can just check the __file__ variable in your module to get the name of the file it was loaded from. Just create your file in that same directory (preferably using os.path.dirname and os.path.join to remain platform-independent).

Upvotes: 0

Related Questions