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!

Answer from Acorn on Stack Overflow
🌐
Reddit
reddit.com › r/learnprogramming › total noob - how do i properly refer to a file path in python?
r/learnprogramming on Reddit: Total Noob - How do I properly refer to a file path in python?
June 30, 2023 -

Hello,

I am trying to write in the path "c:/gpt-2-2/models" into a python code. When I run the code I get a syntax error at the "C:" part. I guess I don't know how to properly write file paths in python. Any help would be appreciated.

Discussions

formatting - What is the preferred way to write a file path in Python - Stack Overflow
When writing a file path in python, I have seen several variations to write the syntax and I was curious if there is just one preferred way: the examples are: myFile= r"C:\My Documents\test\hello.... More on stackoverflow.com
🌐 stackoverflow.com
Python Write File Path into Files - Stack Overflow
I have the following problem: I have a folder with files. I want to write into those files their respective file path + filename (home/text.txt) . How can I achieve this in python? Thanks in advanc... More on stackoverflow.com
🌐 stackoverflow.com
August 11, 2020
python - How do I create a file at a specific path? - Stack Overflow
The besty practice is to use '/' and a so called 'raw string' to define file path in Python. ... However, a normal program may not have the permission to write in the C: drive root directory. More on stackoverflow.com
🌐 stackoverflow.com
Create file if it doesn't exist, as well as its folders?
Much more readable (imo), and works on any OS: from pathlib import Path output_file = Path("/some/path/file.txt") output_file.parent.mkdir(exist_ok=True, parents=True) output_file.write_text("some text") Would recommend using the following for writing to the file though (handles closing the file for you, stream handling etc.) with open(output_file, 'w') as file: file.write("some text") More on reddit.com
🌐 r/learnpython
26
64
August 5, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › python › create-a-file-path-with-variables-in-python
Create a File Path with Variables in Python - GeeksforGeeks
July 23, 2025 - Python’s os.path.join() function can also be used to handle file paths, as it automatically handles platform-specific path separators (/ for Linux/macOS and \ for Windows). ... import os bp = "/path/to" fn = "example.txt" fp = os.path.join(bp, ...
🌐
Python
docs.python.org › 3 › library › pathlib.html
pathlib — Object-oriented filesystem paths
February 23, 2026 - Create a file at this given path. If mode is given, it is combined with the process’s umask value to determine the file mode and access flags. If the file already exists, the function succeeds when exist_ok is true (and its modification time is updated to the current time), otherwise FileExistsError is raised. ... The open(), write_text() and write_bytes() methods are often used to create files.
🌐
University of Pittsburgh
sites.pitt.edu › ~naraehan › python3 › file_path_cwd.html
Python 3 Notes: File Path and CWD
Python 3 Notes [ HOME | LING 1330/2330 ] File Path and CWD << Previous Note Next Note >> On this page: open(), file path, CWD ('current working directory'), r 'raw string' prefix, os.getcwd(), os.chdir(). Referencing a File with a Full Path and Name As seen in Tutorials #12 and #13, you can ...
🌐
Python
docs.python.org › 3 › library › os.path.html
os.path — Common pathname manipulations
This module implements some useful functions on pathnames. To read or write files see open(), and for accessing the filesystem see the os module.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 63349411 › python-write-file-path-into-files
Python Write File Path into Files - Stack Overflow
August 11, 2020 - Of course, as Landon said, you can simply do this by using with, which will close the file for you after you are done writing to it: with open("path") as file: file.write("same string here") This second snippet only takes up 2 lines, and it is the common way of opening a file.
🌐
W3Schools
w3schools.com › python › python_file_write.asp
Python File Write
Note: If the file already exists, an error will be raised. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
GeeksforGeeks
geeksforgeeks.org › python › writing-to-file-in-python
Writing to file in Python - GeeksforGeeks
3 weeks ago - Example: The following code writes a small sequence of bytes into a file called file.bin and then reads it back in binary mode. ... pathlib provides an object-oriented way to work with files and paths.
🌐
LearnPython.com
learnpython.com › blog › write-to-file-python
How to Write to File in Python | LearnPython.com
It is important to note that pathlib has greater portability between operating systems and is therefore preferred. We can use the Path().write_text() method from pathlib to write text to a file.
🌐
Inspired Python
inspiredpython.com › tip › python-pathlib-tips-reading-from-and-writing-to-files
Python Pathlib Tips: Reading from and Writing to Files • Inspired Python
>>> from pathlib import Path >>> p = Path('/tmp/inspiredpython.txt') >>> p.write_text('Hello from Inspired Python') >>> p.read_text() 'Hello from Inspired Python' ... You can use the pathlib module’s Path() class to read and write to files directly, circumventing the need for open() if you don’t need access to the file object.
🌐
Automate the Boring Stuff
automatetheboringstuff.com › chapter8
Automate the Boring Stuff with Python
Since C:\Python34 was the working directory when os.path.abspath() was called, the “single-dot” folder represents the absolute path 'C:\\Python34'. Since your system probably has different files and folders on it than mine, you won’t be able to follow every example in this chapter exactly.
🌐
Python Examples
pythonexamples.org › python-write-to-file
Python - Write to File
Now, let us go through some examples, covering the above said ways of writing to a file in Python. In the following program, we shall open a file named "data.txt" in write mode, and write the text in a string variable to the file, using write() method. file_path = "data.txt" content = "Hello World!
🌐
Python Cheatsheet
pythoncheatsheet.org › home › file directory path
File and directory Paths - Python Cheatsheet
On Windows, paths are written using backslashes (\) as the separator between folder names. On Unix based operating system such as macOS, Linux, and BSDs, the forward slash (/) is used as the path separator.
🌐
Finxter
blog.finxter.com › home › learn python blog › how to save a text file to another folder in python
How to Save a Text File to Another Folder in Python - Be on the Right Side of Change
September 28, 2022 - This function concatenates the file path and the filename and saves it to file_path. Then, the if statement checks for the existence of the specified folder. If this folder does not exist, one is created calling os.mkdir() and passing the folder to create as an argument. The following section opens the two (2) files as indicated above in Method 1 and writes the contents of file 1 (fp1) to file 2 (fp2).
🌐
Medium
medium.com › @ageitgey › python-3-quick-tip-the-easy-way-to-deal-with-file-paths-on-windows-mac-and-linux-11a072b58d5f
Python 3 Quick Tip: The easy way to deal with file paths on Windows, Mac and Linux | by Adam Geitgey | Medium
January 31, 2018 - If you want your Python code to work on both Windows and Mac/Linux, you’ll need to deal with these kinds of platform-specific issues. Luckily, Python 3 has a new module called pathlib that makes working with files nearly painless.
🌐
Reddit
reddit.com › r/learnpython › create file if it doesn't exist, as well as its folders?
r/learnpython on Reddit: Create file if it doesn't exist, as well as its folders?
August 5, 2022 -

I have the following code:

file = open('folder/subfolder/file.txt', 'w')
file.write('hello world')
file.close()

I get an error, however: FileNotFoundError: [Errno 2] No such file or directory

So naturally, I googled how to write to a file, creating it if it doesn't exist. And all the solutions are the same: Do what I did, but it only works if there's no missing subfolders.

How would I create the folder and subfolder (if they don't exist), and then write the file?

I suppose I could split the string, loop through each folder, and test for their existence. But is there a cleaner way to do this? It seems odd python is smart enough to create the file, but not enough to create the directory it's in as well.

🌐
Delft Stack
delftstack.com › home › howto › python › set file path python
How to Set File Path in Python | Delft Stack
February 14, 2024 - We can use raw string literals to provide paths for the files as a raw string will treat these backslashes as a literal character. To make a raw string, note that we have to write the (r) character before the quotes for the string.