Open function does not create a file?

I am using colab to run a Physics Python program for homework. The program seems to work but it does not create the data file it is supposed to. I have a short test code that shows the problem:

filename = "G:\data.txt"
file = open(filename, "w+")
if file:
    file.write("Testing.")
    file.close()
    print("Wrote 'Testing.' to file", filename, ".\n")
else:
    print("File", filename, "failed to open.\n")

The above code generates output:
Wrote ‘Testing.’ to file G:\data.txt .
but the file G:\data.txt is not created!?
What am I doing wrong?

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

I’m assuming the data.txt file does not exist yet since you said you want it to be created.

I really suggest you looking into Python file handling. filename = "G:\data.txt" does not mean that Python will look into your cwd for a file with that name. You’ve only made a variable, filename, and you’ve given that a value containing a string. Therefore open() won’t do anything since you’re literally opening a string instead of a file.

You can create a file like so:

file = open("give_a_filename.txt", "x")

“x” will create a file and returns an error if the file already exist. So now you’ve created a file called “give_a_filename.txt”!

You can write something to this file with:

f = open("give_a_filename.txt", "w") #w for write 
f.write("Add content to the file")
f.close()

Take a look at these sites: file handling, information regarding working directory

Let me know if you have any other questions or if anything is unclear

After some further investigation I got my code to work. The problem is not the mode for the open function. Here is the Python "man"page for ‘w’ mode:
‘w’ Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.

The problem is that the Google colab environment does not write to local files unless you do something to link the colab with the local file. See this link:

Fortunately I already have a Google drive, so I was able to just link it to my desktop. After that my programs worked unaltered.

The reason I was using the colab environment was because the program imported functions from the numpy library, but “pip install numpy” failed for my 3.9.10 Python environment (see: python - Getting an error saying "Could not build wheels for numpy which use PEP 517 and cannot be installed directly" while installing numpy - Stack Overflow).