Telling Python To Save A .txt File To A Certain Directory On Windows And Mac
Solution 1:
Just use an absolute path when opening the filehandle for writing.
import os.path
save_path = 'C:/example/'
name_of_file = raw_input("What is the name of the file: ")
completeName = os.path.join(save_path, name_of_file+".txt")
file1 = open(completeName, "w")
toFile = raw_input("Write what you want into the field")
file1.write(toFile)
file1.close()
You could optionally combine this with os.path.abspath()
as described in Bryan's answer to automatically get the path of a user's Documents folder. Cheers!
Solution 2:
Use os.path.join to combine the path to the Documents
directory with the completeName
(filename?) supplied by the user.
import os
with open(os.path.join('/path/to/Documents',completeName), "w") as file1:
toFile = raw_input("Write what you want into the field")
file1.write(toFile)
If you want the Documents
directory to be relative to the user's home directory, you could use something like:
os.path.join(os.path.expanduser('~'),'Documents',completeName)
Others have proposed using os.path.abspath
. Note that os.path.abspath
does not resolve '~'
to the user's home directory:
In [10]: cd /tmp
/tmp
In [11]: os.path.abspath("~")
Out[11]: '/tmp/~'
Solution 3:
A small update to this. raw_input()
is renamed as input()
in Python 3.
Solution 4:
Another simple way without using import OS is,
outFileName="F:\\folder\\folder\\filename.txt"
outFile=open(outFileName, "w")
outFile.write("""Hello my name is ABCD""")
outFile.close()
Solution 5:
If you want to save a file to a particular DIRECTORY and FILENAME here is some simple example. It also checks to see if the directory has or has not been created.
import os.path
directory = './html/'
filename = "file.html"
file_path = os.path.join(directory, filename)
ifnotos.path.isdir(directory):
os.mkdir(directory)
file = open(file_path, "w")
file.write(html)
file.close()
Hope this helps you!
Post a Comment for "Telling Python To Save A .txt File To A Certain Directory On Windows And Mac"