开发者

Python3:Save File to Specified Location

I 开发者_如何学Gohave 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.


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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜