[python] How to create a new text file using Python

I'm practicing the management of .txt files in python. I've been reading about it and found that if I try to open a file that doesn't exists yet it will create it on the same directory from where the program is being executed. The problem comes that when I try to open it, I get this error:

IOError: [Errno 2] No such file or directory: 'C:\Users\myusername\PycharmProjects\Tests\copy.txt'.

I even tried specifying a path as you can see in the error.

import os
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
my_file = os.path.join(THIS_FOLDER, 'copy.txt')

This question is related to python python-2.7

The answer is


    file = open("path/of/file/(optional)/filename.txt", "w") #a=append,w=write,r=read
    any_string = "Hello\nWorld"
    file.write(any_string)
    file.close()

# Method 1
f = open("Path/To/Your/File.txt", "w")   # 'r' for reading and 'w' for writing
f.write("Hello World from " + f.name)    # Write inside file 
f.close()                                # Close file 

# Method 2
with open("Path/To/Your/File.txt", "w") as f:   # Opens file and casts as f 
    f.write("Hello World form " + f.name)       # Writing
    # File closed automatically

There are many more methods but these two are most common. Hope this helped!


f = open("Path/To/Your/File.txt", "w")   # 'r' for reading and 'w' for writing
f.write("Hello World from " + f.name)    # Write inside file 
f.close()                                # Close file 

# Method 2shush
with open("Path/To/Your/File.txt", "w") as f:   # Opens file and casts as f 
    f.write("Hello World form " + f.name)       # Writing
# File closed automatically