Telling Python to save a .txt file to a certain directory on Windows and Mac

后端 未结 7 1191
无人共我
无人共我 2020-11-28 19:55

How do you tell Python where to save a text file?

For example, my computer is running the Python file off my desktop. I want it to save all the text file in my docum

7条回答
  •  孤街浪徒
    2020-11-28 20:35

    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!

提交回复
热议问题